DEV Community

Cover image for Adding an API and database to your Nuxt App with Prisma

Adding an API and database to your Nuxt App with Prisma

Ruheni Alex on February 18, 2021

Note: The application is built using Nuxt version 2 at the time it was written. Prisma runs on the server-side and you can use Nuxt version 3's se...
Collapse
 
ruheni profile image
Ruheni Alex

I appreciate the feedback.

At the time of writing, the article used Nuxt v2. However, it should be possible with Nuxt 3 without Express. I would recommend checking out sidebase.io which is more up to date. 🙂

Collapse
 
axelbriche profile image
AxelBriche • Edited

Is it possible to use prisma with Nuxt 3 and /server/api folder for useAsyncData/useFetch methods (for send form data) without Express?

I don't find find how to sent (PUT/POST) my form data with useAsyncData/useFetch.
And Nuxt 3 come with the /server/api dir, why use Express?

Collapse
 
ruheni profile image
Ruheni Alex

Hi Axel 👋🏽

At the time the guide was written, the sample application was using Nuxt 2 (I'll add a note about this). You can exclude Express in your project. You can still use Prisma with in server routes.

Collapse
 
albie214 profile image
Aldwin Filoteo

how can we fetch data from database without using Express ? can we have samples using nuxt 2 . thank you

Collapse
 
gazreyn profile image
Gareth

This was almost a year ago so I'm pretty sure you worked it out between then and now.

Image description

And then you'd just call const { data } = await useFetch('/api/user/1'); in app.vue or which ever Vue component you'd like.

Collapse
 
liamb profile image
liamb13 • Edited

If I had an array of posts pulled from another api. How could I add them in bulk to prismas?

E.g:

result = [
  {
    title: 'Post Title 1',
    content: 'An example post',
    author: 'liam@example.com',
  },
    {
    title: 'Post Title 2',
    content: 'An example post by a different author',
    author: 'liamb@example.com',
  },
]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
liamb profile image
liamb13

The age old adage... 'read the docs'

const createMany = await prisma.user.createMany({
  data: result,
  skipDuplicates: true, // Skip 'Bobo'
})
Enter fullscreen mode Exit fullscreen mode

or replace result with:

data = [
  {
    title: 'Post Title 1',
    content: 'An example post',
    author: 'liam@example.com',
  },
    {
    title: 'Post Title 2',
    content: 'An example post by a different author',
    author: 'liamb@example.com',
  },
]
Enter fullscreen mode Exit fullscreen mode

Reference: Create multiple records

Collapse
 
atinux profile image
Sébastien Chopin

Great article 🙌

Collapse
 
manojap profile image
MANOJ AP

do you configure database properly ? double check schema..... try to run the migrate command

also try npx prisma studio ( for make sure the connection is set properly)

Collapse
 
evilme profile image
Nathalie Magdalena Schönwetter

Hi, did you mean me? Yes the DB is running in dev mode. prisma studio is also running. When i try to build, generate and start the nuxt app the api is not available.

Collapse
 
rawalprashant profile image
Prashant Raval

How to use or call this API in vue file to display result data? Can you please share example?

Collapse
 
ruheni profile image
Ruheni Alex

Hi Prashant 👋🏽

You can use the fetch, axios or http nuxt modules to fetch call the API in either your component or page as follows:

export default {
  data: () => ({
    posts: [],
  }),
  async fetch() {
    this.posts = await this.$http.$get("/posts");
  },
};
Enter fullscreen mode Exit fullscreen mode

You can choose how you would like to display your data in the view.

Collapse
 
rawalprashant profile image
Prashant Raval

Hi Alex,

Thanks for your response, well the thing is i am starting with Nuxt 3 so later i don't have to rewrite my project, and nuxt 3 have no support for axios.

Nuxt 3 having fetch option and h3, but i am not sure how to use them as Post method to submit my form data.

So do you have any idea about that?

Regards,

Thread Thread
 
ruheni profile image
Ruheni Alex

For a form submission, you can still use fetch to submit data to the API route.

We created a rest-nuxtjs example but it uses Nuxt v2 and a custom server. In that example, the create.vue page makes a form submission to an API route. You can use this example for inspiration when handling form submission in your application.

Here's what the function resembles:

export default {
  data() {
    return { title: '', authorEmail: '', content: '' }
  },
  methods: {
    createDraft: async function (e) {
      e.preventDefault()
      const body = {
        title: this.title,
        authorEmail: this.authorEmail,
        content: this.content,
      }
      try {
        const res = await fetch(`/api/post`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        })
        const data = await res.json()
        await this.$router.push({ name: 'drafts' })
      } catch (error) {
        console.error(error)
      }
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

Let me know if you run into any other issues. I'd be happy to help! 🙂

Thread Thread
 
rawalprashant profile image
Prashant Raval

Hello Alex,

Before i test your example code for form submission, i am stuck with the API call, i have created a file server/api/index.js and here its code part


import express from 'express'
import pkg from '@prisma/client';
const { PrismaClient } = pkg;

const prisma = new PrismaClient({
    log: ['query']
})

const app = express()

// Body parser, to access `req.body`
app.use(express.json())

app.get('/apitest', async (req, res) => {
    res.end('Test API!')
})

app.post('/sendMessage', async (req, res) => {
    const { name, email, company_name, phone, message } = req.body
    const post = await prisma.contact.create({
        data: {
            name,
            email,
            company_name,
            phone,
            message
        }
    })
    res.status(200).json(post)
})

Enter fullscreen mode Exit fullscreen mode

Now, when i run the server localhost:3000 it says handle is not a function
with error code 500

i think as per nuxt 3 document for API ( v3.nuxtjs.org/docs/directory-struc... ) might be it has its own way to handle the request,

So, did you have ever tried this kind of call and have any suggestion for me to fix it?

Thanks a lot

Collapse
 
mbarari profile image
Mojtaba Barari

Great job!! Tanx! also a question! I wanna import an DB from server on local to work offline. should I write the schema of main server BD before import for prisma to work??

Collapse
 
ruheni profile image
Ruheni Alex

Hey Mojtaba 👋

If you're referring to the database schema, you can use the db pull command that the Prisma CLI provides to introspect your database. You can then change the DATABASE_URL in the .env file from the main server to your local database instance, run db push or prisma migrate dev to apply the schema to your local database as well as generate a new Prisma Client.

Collapse
 
mbarari profile image
Mojtaba Barari • Edited

Tanx. BTW a final question that you may know the answer to.
I'm trying to build an electron app with nuxt-prisma-sqlite . on dev everything is ok, but on built exe file my api wont be handled by express and it gives 404.
Did you have ever came across this??

Collapse
 
manojap profile image
MANOJ AP

can I use prisma in Vue component as I do in React and Next

Collapse
 
ruheni profile image
Ruheni Alex

Hey Manoj, 👋🏽

Prisma runs on the server-side. If you're using Nuxt, you can run Prisma in the asyncData and fetch hooks at either a page or component level.

I created a small demo you can check out experimenting how this would work. Your feedback on this would be appreciated too 🙂

Collapse
 
manojap profile image
MANOJ AP

I managed to create a middleware API in Nuxt
I also tried PrismaClient as Vue plugin(Vue.use) and it fails.
Same result in Vuex store.

gist.github.com/manojap/fb0d973551...

Thread Thread
 
manojap profile image
MANOJ AP
Thread Thread
 
ruheni profile image
Ruheni Alex

The sample on Codesandbox should work just fine. I've managed to query data – both the REST and GraphQL API.

Could you share the error you get when you use a Vue plugin?

Collapse
 
liamb profile image
liamb13

Would it be possible to expand on this article for user authentication?

Collapse
 
ruheni profile image
Ruheni Alex

Hi @liamb 👋

That sounds like a terrific idea, similar to How to Build a Fullstack App with Next.js, Prisma, and PostgreSQL. Before we get to it, you can have a look at nuxt-auth.

Collapse
 
hendisantika profile image
Hendi Santika

Could You upgrade into nuxt 3?

Collapse
 
manojap profile image
MANOJ AP

right solution

Collapse
 
bastianhilton profile image
Sebastian hilton

I know its been several months since this post, but how does someone create API routes if you have hundreds of models? Is there an easier way or a generator?

Collapse
 
ruheni profile image
Ruheni Alex

Hi Sebastian 👋🏽
The API routes defined would be depended on the business logic of your application. However, if you're looking to build a generator, take a look at create-prisma-generator. However, the API for building generators is unofficial and undocumented.

Collapse
 
evilme profile image
Nathalie Magdalena Schönwetter

Hoi, how can i build this correctly? Everytime i try npm run build, generate and start the frontend works fine but the backend (api) is not reachable.