Run GraphQL server with Express in NuxtJS
Since I use Vue for almost all of my projects, if I’m making an application that requires routing and server side rendering (for SEO), I use NuxtJS.
NuxtJS is a framework where you can create a server side rendering app using VueJs. One of the things people struggle with NuxtJS is how to use an Express server together with NuxtJs to handle a REST API.
In this post I’m going to show you how you can use a GraphQL server to create an API that will power a NuxtJs project.
Requirements
You should know about NodeJs, Express, GraphQL and NuxtJS to get started, even if you don’t know NuxtJS and Express you should have a basic knowledge in Javascript and NodeJs.
- NodeJs 14+
- ExpressJs 4+
- NuxtJs 2.14+
- GraphQL
- NPM or Yarn (I’m using NPM)
- GraphQL express middleware
Create your NuxtJS project
First step is to create your Nuxtjs project.
npx create-nuxt-app GraphQL
My project will be created inside the GraphQL folder, you will be asked some basic questions, to select a CSS framework, the package manager etc, just answer the questions (it won’t matter much for this tutorial).
You can read more about creating NuxtJs project here – https://nuxtjs.org/docs/2.x/get-started/installation
Install required packages
Now you will have to install the required packages, this include express, GraphQL, GraphQL express middleware.
cd GraphQL
npm install graphql express express-graphql
Once the installation is complete you can proceed to the next steps
Create your express server
Now you need to create an express server
mkdir server
const express = require('express')
const {graphqlHTTP} = require('express-graphql')
const gSchema = require('./graph/index')
const app = express()
app.use('/', graphqlHTTP({
schema: gSchema,
graphiql: true
}))
module.exports = app
Here you can see that we are not creating a usual Express server, which listens to a port, instead we will be creating an express server and pass it to the server middleware at Nuxt.
Create a basic GraphQL schema
mkdir graph
cd graph
vim index.js
Once you created the GraphQL schema at the `./graph/index.js`. I’m not going to detail how you can create a GrpahQL schema, the purpose of this tutorial is to create a GraphQL server by using express and Nuxt.
Add your Express server to the server middleware at nuxtconfig.js
Open the nuxt.config.js file located on the root of your project folder, the nuxt.config.js file contains all the necessary settings for your Nuxt project.
Add the server middleware property to your nuxt.config.js file
serverMiddleware: [ { path: "/graph", handler: "~/server/index.js" }, ],
Run your Nuxt project
Fire your nuxt project
npm run dev
This will start your nuxt project, which is usually port 3000 by default.
Now goto http://localhost:3000/grapqh
And you should be get the GraphiqL visual editor that you can test GraphQL queries.
Happy coding.
Comments ()