How to integrate Strapi-graphql in Nuxt 2

How to configure strapi CMS using graphql in Nuxt


Strapi a opensource headless CMS for developing content rich applications using Javascript.

Nuxt is a framework on top of the Vue progressive JavaScript framework. Along with Vuejs it offers fast development, with minimal bundle size and performance upgrade over other frameworks.

Integrating Strapi using Apollo in Nuxt

Strapi exposes API for each collection types and have corresponding API end points. So graphql can consume it.

Graphql allow us to query data required. May be we not need the entire REST API data. Graphql can installed as on strapi with zero configuration. Once you are ready with strapi configure Apollo using the nuxt module.

Configure @nuxt/apollo

Install the strapi dependency

yarn add --dev @nuxtjs/apollo

also need to configure the nuxt config.

export default {
  modules: ['@nuxtjs/apollo',
  ],
   apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: process.env.BACKEND_URL || "http://localhost:1337/graphql",
      }
    }
  },
}

Gql queries ?

Let’s prepare our first Graphql query. In the project add a folder apollo/queries/category/articles-categories.gql with following

    query {
      categories {
        data {
          id
          attributes {
            name
          }
        }
      }
    }

Executing Graphql queries in Page component

In the index.vue page or in any page we can execute the query as follows

 <script>
    import articlesQuery from "~/apollo/queries/categoris/articles-categories";
    
    export default {
      data() {
        return {
          category: {
            data: [],
          },
        };
      },
      
      apollo: {
        category: {
          prefetch: true,
          query: articlesQuery,
          variables() {
            return { id: parseInt(this.$route.params.id) };
          },
        },
      },
    };
    </script>

Editor frameworks for JS apps

About Javascript Editor frameworks


If you are building content based application such as blog, may want featured editor, such as Post editor or comment box. Making such an editor with all formatting capabilities would be tiresome.

Editor frameworks and wrapper libraries help us achieve this goal with ease and peace. I don’t intended to review each of these , instead I would to list best of them and in the up coming posts we will learn using these awesome editor frameworks.

My Picks

I like block editor mostly for content management, in my react app I will choose the Editor.js . It is easy to configure and use.

Second most useful framework for content management is Drftjs , which is maintained by Facebook itself. It is a complete Editor framework featuring mention, hashtag etc and it’s flexible too.

Here is complete list of framework available for building a full featured editor in your next JS / React/Vue/Angular app

How to setup MongoDB in Prisma

How to configure Prima ORM witn MongoDB NoSQL database


Prisma is a ORM for JavaScript and Typescript, it let developers easily configure, create / migrate databases using models. One of the cool feature I love mostly is that , it can be configured with few CLI commands like init, migrate

Setup Prisma

For initializing the Prisma install the developer dependency npm i -d prisma and initialize prisma with

npx prisma init

It will generate necessary files under Prisma folder, please open the file and configure database and models. For demonstration I have configured a Sqlite database, you can use other databases like mysql, postgres, Mongodb etc.

  • Prisma MongoDB connection

    Prisma is a Typescript based ORM for Javascript Frameworks such as React, Vuejs and Angular. It allows developers easily configure database and hand data using model classes.

    Mongo DB

    MongoDB is a NoSQL database for web, primarily. It is widely used in cloud based web and Mobile application.

    How to configure MongoDB on Prima

    In Prisma configuration file we can use preview version on MongoDB driver. The connection string can be stored in .env file (at the route of your project).

    Local database

    Form local database we can use the following connection string

    //.env
     DATABASE_URL = mongodb://localhost:27017/blogdata?retryWrites=true&w=majority

    Mongo Atlas database

    For cloud based Mongo database we have to rely on the following connection.

    //.env
     DATABASE_URL = mongodb+srv://admin:RRHEfMsK8zHWsGTI@cluster0.cqnll.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

    schema.prisma

    Finally the Prisma Schema file would look like the following,

    </p>
    datasource db {
      provider = "mongodb"
      url      = env("DATABASE_URL")
    }
    
    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["mongodb"]
    }
    
    model User {
    
      id    String @id @default(auto()) @map("_id") @db.ObjectId
    
      email String
    
    } 
    <p>

    Migrating DB

    If you are familiar with Prisma and Schema, we used to run migrate command to update the database with model.

    There is an exception for Mongo, you don’t need to Migrate, instead run npx prisma generate command after any change made to schema.

    To update the model we use npx prisma db push command.

Prismic-CMS-Nuxt slice rendering

Prismic-CMS-Nuxt slice rendering example


This is a Prismic-CMS-Nuxt slice rendering example

<template>
<div class="container">
<div class="flex">
<slice-zone class="subtitle"
:slices="page.data.body1"
:resolver="resolver" />
</div>
</div>
</template>
<script>
import SliceZone from "vue-slicezone";
import * as Slices from "@/slices";
export default {
mounted() {},
async asyncData({ $prismic }) {
return {
page: await $prismic.api.getSingle("home"),
};
},
components: {
SliceZone,
},
data() {
return {
};
},
methods: {
resolver({ sliceName, slice, i }) {
return Slices[sliceName];
},
},
};
</script>

Prismic-CMS-Nuxt store

Prismic-CMS-Nuxt store example


This is a Prismic-CMS-Nuxt store example

export const state = () => ({
snippets: Object,
isLoaded: false,
})
export const actions = {
async loadSnippets({ commit }) {
const document = await this.$prismic.api.query(
this.$prismic.predicates.at("document.type", "snippet_type")
);
commit('setSnippet', document);
commit('setLoaded', true);
}
}
export const mutations = {
setSnippet(state, code) {
state.snippets = code
},
setLoaded(state, loaded) {
state.isLoaded = loaded
}
}

Keystone CMS authentication in Nuxtjs

Keystone CMS authentication snippet for Nuxtjs


This is Nuxt 2 Keystone authentication snippet

const { Keystone } = require('@keystonejs/keystone');
const { Password, Text, Relationship, Checkbox } = require('@keystonejs/fields');
const { GraphQLApp } = require('@keystonejs/app-graphql');
const { AdminUIApp } = require('@keystonejs/app-admin-ui');
const { NuxtApp } = require('@keystonejs/app-nuxt');
const { MongooseAdapter: Adapter } = require('@keystonejs/adapter-mongoose');
const PROJECT_NAME = 'key-app';
const adapterConfig = { mongoUri: 'mongodb://localhost/key-app' };
const { PasswordAuthStrategy } = require('@keystonejs/auth-password')
const keystone = new Keystone({
adapter: new Adapter(adapterConfig),
});
keystone.createList('Todo', {
schemaDoc: 'A list of things which need to be done',
fields: {
name: { type: Text, schemaDoc: 'This is the thing you need to do' },
assignedTo: {
type: Relationship,
ref: 'User',
many: false,
isRequired: true
}
},
});
keystone.createList('User', {
schemaDoc: 'A list of users',
fields: {
name: {
type: Text,
isUnique: true,
isRequired: true
},
isAdmin: {
type: Checkbox,
isRequired: true
},
password: {
type: Password,
isRequired: true
}
},
});
const authStrategy = keystone.createAuthStrategy(
{
type: PasswordAuthStrategy,
list: 'User',
config: {
identityField: 'name',
secretField: 'password'
}
}
)
module.exports = {
keystone,
apps: [
new GraphQLApp(),
new AdminUIApp({
name: PROJECT_NAME, authStrategy,
}),
new NuxtApp({
srcDir: 'src',
buildDir: 'dist',
}),
],
};
view raw index.js hosted with ❤ by GitHub

Nuxt 2 ServerMiddleware

Nuxt server middle ware configuration


This is a Nuxt 2 server Middle Ware snippet

import colors from 'vuetify/es5/util/colors'
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
serverMiddleware:[
'~/api/index.ts',
] ,
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
titleTemplate: '%s - app_tmpl',
title: 'app_tmpl',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/typescript
'@nuxt/typescript-build',
// https://go.nuxtjs.dev/vuetify
'@nuxtjs/vuetify',
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
],
// Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify
vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
dark: true,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
}
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
}
}
view raw nuxt-config.js hosted with ❤ by GitHub
import express from "express";
import { PrismaClient, Todo } from "@prisma/client";
const app = express();
const prisma = new PrismaClient();
app.use(express.json());
app.get("/", (req, res) => {
res.json("Wlcome to API");
});
app.get("/todos", async (req, res) => {
const todos = await prisma.todo.findMany();
res.json(todos);
});
export default {
path: "/api",
handler: app
};

On GitHub , All Gits

How to use Prisma ORM with Nuxt3

How to use prisma ORM in Nuxt3


Prisma help developers configuring database and fetching data asynchronously. We can use Prisma with relational database and nosql databases like MongoDB.

Nuxt Prisma Setup

From the project access the terminal and issue the command to initialize which will create schema files and folder structure. This step is similar to Nuxt2.

npx prisma init

Configure database and schema and use migrate command to build the database structure.

npx prisma migrate dev --name firstmigration

After the successful migration we can use npm prisma studio for managing the data. Also a standalone studio app is available.

Prisma Client in Nuxt3

Prisma client configuration can be tricky in Nuxt3. Prisma is not a special package for Nuxt3, so we have to first extract the package and then destructor the the PrismaClient.

Let’s install the prisma client dependency

yarn add @prisma/client

The following is an API async function which use PrismaClient for data fetching.

</p>
import type { IncomingMessage, ServerResponse } from 'http'

  import   prisma from "@prisma/client";
  const {PrismaClient} = prisma;
  const client = new PrismaClient()

export default async (req:IncomingMessage, res:ServerResponse) => {    
   const tags = await client.tag.findMany()
    return {
     tags: tags 
    }
  }
<p>

From the prisma package we destructor the PrismaClient object and create variable of the client. In Nuxt2 we can use

</p>
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
<p>

How to create API end points in Nuxt3

How to implement API end point in Nuxt3


Nuxt3 is in beta with Vue3, lots of cool features , wow . I am excited.

How to create a API end point in Nuxt3 ?

Nuxt3 come with a dedicated server folder for API, how do we configure a RSET API?

Does it require nuxt-config settings for setting up a middleware or something ? No.

Do the following

  • Create folder server/api in the root of the project
  • Create API end point files Nuxt way or in Nodejs way

Nuxt style

The api files export a default function (asynfunction) that handles api requests.

//api1.ts
import type { IncomingMessage, ServerResponse } from 'http'
export default async (req, res) => {
  await someAsyncFunction()

  return {
    someData: true
  }
}

Node style route

We can also create API file as Nodejs style function which use res.end function to send response.

//api2.ts
import type { IncomingMessage, ServerResponse } from 'http'
import type { IncomingMessage, ServerResponse } from 'http'

export default async (req: IncomingMessage, res: ServerResponse) => {
  res.statusCode = 200
  res.end('Works!')
}

What’s Next ? Implement some data logic for end points with Prisma. I saved those thought for next Next3 post.

How to getting started with Nuxt3

How to setup Nuxt3 project


Nuxt3 is in beta with Vue3 awesome computing capabilities. What’s the first step to Nuxt2 to Nuxt3.

Well we need to update the latest Nodejs , so head over Nodejs Official site, download, install.

Use the new Nuxt3 CLI to create boiler plate template for the project.

npx nuxi init <project-name>

This will initialize the project structure, lets install dependencies

yarn install
or
npm install

You may note that there is lots of missing folders on project structure, such as pages, plugins, middleware etc. Pages are optional in Nux3, means you can manage pure Vue3 projects in Nuxt3.

Now run the project with yarn dev .