Where to do database calls?

Hello, I need to fetch data from my database using Prisma. The data should then be displayed on my page. Of course, reading the database should only happen server-side. Where would I do that in Nuxt? If I understood correctly, <script setup> might also run on the client, right?
2 Replies
kapa.ai
kapa.ai2mo ago
Hi @battlesheep123. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To fetch data from your database using Prisma and ensure the database access happens only server-side in Nuxt, you should perform the database call inside a server route (API route) located in the server/api/ directory. Then, from your page or component, you fetch the data from this API route using useFetch or useAsyncData. Here's why: - Code in <script setup> can run on both the server and the client, depending on the rendering context. Directly calling Prisma in <script setup> would risk exposing your database to the client, which is not secure. - Server routes in server/api/ are only executed on the server, so you can safely use Prisma there. Example structure: 1. Create a server API route:
server/api/posts.ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default defineEventHandler(async (event) => {
return await prisma.post.findMany()
})

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default defineEventHandler(async (event) => {
return await prisma.post.findMany()
})

2. Fetch data in your page/component:
pages/index.vue
<script setup lang="ts">
const { data: posts } = await useFetch('/api/posts')
</script>

<template>
<div v-for="post in posts" :key="post.id">
{{ post.title }}
</div>
</template>

<script setup lang="ts">
const { data: posts } = await useFetch('/api/posts')
</script>

<template>
<div v-for="post in posts" :key="post.id">
{{ post.title }}
</div>
</template>

This approach ensures that your database logic is strictly server-side, and your client-side code only interacts with the API endpoint, never directly with Prisma or your database. For more details, see the Nuxt documentation on data fetching and the distinction between $fetch, useFetch, and server routes. The docs emphasize that <script setup> can run on both server and client, and direct database access should be avoided there for security reasons. Use API routes for server-only logic and fetch data from them in your components Data Fetching. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@796456861318119554> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?