In this article, you will build a blog that will make use of a GraphQL server. We will build the blog app using Apollo client and Vue.
To complete this tutorial, you will need:
This tutorial assumes knowledge of JavaScript and some familiarity with Vue and GraphQL.
This tutorial was verified with Node v14.4.0, npm
v6.14.5, MySQL v14.14, @adonisjs/cli
v4.0.12, @vue/cli
v4.4.6, vue
v2.5.2, graphql
v15.1.0, and apollo-client
v2.6.10.
You can grab the GraphQL server so you can follow along with the tutorial.
Once you have cloned the repo, navigate to the GraphQL server project directory:
Install the required packages:
Copy .env.example
to .env
:
Edit the .env
file as necessary so the database information provides proper credentials for a MySQL database you have running. DB_USER
and DB_PASSWORD
may need to be changed.
Generate a key for Adonis:
Migrate the database configurations:
The GraphQL server was built with AdonisJS. AdonisJS provides a package that we can use to handle Cross-Origin Resource Sharing (CORS) on our API. By default CORS is turned off on AdonisJS, so we need to enable it.
To enable CORS on AdonisJS app, we set origin
to true
in config/cors.js
as below:
The cloned GraphQL server has CORS already enabled but it’s worth mentioning it.
Since our blog app will be making use of the GraphQL server, we’ll need to start the server and keep it running for the rest of the tutorial.
To do start, ensure that you are in the GraphQL server project directory and run the command below:
This will start the GraphQL server and keep it running.
The rest of the tutorial assumes you already started the GraphQL server and it is running.
With that taken care of, let’s start building our blog app.
We’ll start by creating a new Vue app using the Vue CLI:
Note: Modern Vue projects can utilize:
You will be prompted with questions about your project. Here are some of the choices that were made. For this tutorial it will be important to install vue-router
:
? Project name graphql-blog-app
? Project description A Vue.js project
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) npm
This will create a new Vue app with the name graphql-blog-app
and install its dependencies.
Navigate to the newly created directory:
The application can be run and viewed in the browser at any time by running the following in your terminal:
With the app created, we can move on to installing the necessary packages for building our GraphQL blog app:
Let’s quickly go over each package:
vue-apollo
: An Apollo/GraphQL integration for VueJS. We install the latest version of the plugin that allows us to use all the great features that comes with Apollo client 2.0.graphql
: A reference implementation of GraphQL for JavaScript.apollo-client
: A fully featured, production-ready caching GraphQL client for every server or UI framework.apollo-link
: A standard interface for modifying the control flow of GraphQL requests and fetching GraphQL results.apollo-link-context
: Used to set a context on your operation, which is used by other links further down the chain.apollo-link-http
: Used to get GraphQL results over a network using HTTP fetch.apollo-cache-inmemory
: Cache implementation for Apollo Client 2.0.graphql-tag
: A JavaScript template literal tag that parses GraphQL queries.Next, let’s put the packages to use. We’ll start by creating an ApolloClient
instance and install the VueApollo
plugin. Open src/main.js
and add the code below to it:
We create a new instance of httpLink
with the URL (http://localhost:3333/graphql
) of our GraphQL server. Then we create an Apollo client using the httpLink
created above and specify we want an in-memory cache. Lastly, we install the Vue Apollo plugin.
Next, let’s create an apolloProvider
object that we’ll specify on our root component:
We create a new instance of the Vue Apollo plugin using the apolloClient
created as our default client. Lastly, we make use of the apolloProvider
object by adding it in our Vue instance, the same way we would use Vue router.
For the purpose of this tutorial, we’ll be using Bulma CSS. So, let’s add it in. Open index.html
and update as below:
We reference Bulma on this content delivery network (CDN).
There are some files and code that came along when we created our Vue app which we won’t be using in this tutorial. Let’s remove them so they won’t interfere with our app.
Delete the HelloWorld
component and remove all its references from src/router/index.js
.
The blog will use a generic layout across its pages. In that case, let’s define a layout that all pages will use. To do this, open src/App.vue
and update as below:
We add a header that all pages will use.
Users should be able to signup to our blog app. We’ll create a SignUp
component that will handle that. So, within src/components
create a new Admin
folder. All admin-related components will be created insider this folder.
Before we create the SignUp
component, let’s create a dedicated file that will hold all our GraphQL queries and mutations. We’ll create this file directly inside src
. Create a graphql.js
file inside src
and paste the code below into it:
This is the GraphQL mutation that will handle creating a new user on our GraphQL server. It takes the username, email, and password of a user. These variables will be passed from the SignUp
component.
Next, let’s create the SignUp
component. Within the Admin
folder, create a SignUp.vue
file and paste the code below into it:
This component renders a form for users to signup. Once the form is submitted, a signup
method is called. Within the signup
method, we make use of mutate
method available on this.$apollo
(from the Vue Apollo plugin). We use the SIGNUP_MUTATION
mutation created earlier and pass along the necessary variables. Once the signup process is successful (that is, the user has been created), we redirect the user to the login page (which we’ll create shortly).
Open src/router/index.js
, and add the code below to it:
Now when we visit the /signup
route, we should see our signup form as in the image below:
Let’s add the ability for users to log in. Just as we did with user sign-up, let’s first create the GraphQL mutation. Add the code below to src/graphql.js
:
This GraphQL mutation handles user log-in to our GraphQL server. It takes the email and password of a user.
Next, within the Admin
folder, create a LogIn.vue
file and paste the code below into it:
This component renders a simple form for users to log in. Once the form is submitted, a login
method is called. Within the login
method, we make use of mutate
method. We use the LOGIN_MUTATION
mutation created earlier and pass along the necessary variables. Once the login process is successful, we save the token gotten from our GraphQL server to localStorage and redirect the user.
Open src/router/index.js
, and add the code below to it:
Now when we visit the /login
route, we should see our login form as in the image below:
Before we start fleshing out the admin-ish part of our blog, let’s create a Menu
component that will serve as the sidebar navigational menu. Within the Admin
folder, create a Menu.vue
file and paste the code below into it:
This renders links to some admin sections of our blog app.
In the admin section, we want to be able to see the list of users that have been created. For that, we created a Users
component. But first, let’s write the GraphQL query that will fetch all users created. Add the code below to src/graphql.js
:
This GraphQL query fetches all users from our GraphQL server.
Next, let’s create the Users
component. Within the Admin
folder, create a Users.vue
file and paste the code below into it:
We make use of the Menu
component created earlier. Then we define our data which will be populated once the data is gotten from our GraphQL server. Within the apollo
object, we add our GraphQL query to fetch all users. This makes use of the ALL_USERS_QUERY
we created above. It is important to note that, the name of our data (allUsers
in this case) must be the same name used in our GraphQL query (allUsers
in this case). Once allUsers
is populated with data from our GraphQL server, we display the users in a table by looping through the array of users. We also add a link to view each user’s details.
Open src/router/index.js
, and add the code below to it:
Now when we visit the /admin/users
route, we should see a list of users as in the image below:
In the last section, we add a link to view user details. Now, let’s implement it. Add the code below to src/graphql.js
:
This GraphQL query fetches a user by their ID from our GraphQL server. It takes the ID of the user as an argument. The user ID will be passed from the UserDetails
component.
Next, let’s create the UserDetails
component. Within the Admin
folder, create a UserDetails.vue
file and paste the code below into it:
We display the specified user’s username, email, and the number of posts created. The USER_QUERY
accepts the ID of the user we want to view their details. The user ID is gotten from the route params. That is, given /admin/users/12
, 12 is the ID of a particular user. We need a way to pass this ID to our query. To do this, we make use of reactive parameter by defining a variables
function that returns an object containing the user ID.
Open src/router/index.js
, and add the code below to it. This route should be below all the previous routes:
We should be able to view a particular user detail now:
Only authenticated users can add new posts. So, we need a way to pass an Authorization
header with the user token along with the request to add a new post that will signify the user can actually add new post. With apollo-link-context
, we can easily do this. Open src/main.js
and add the code below to it:
First, we import apollo-link-context
. Then we make use of it to create an authLink
that gets the user token from local storage and return the headers which contains the Authorization header. Lastly, we make use of the authLink
in our Apollo client.
Now, an Authorization header will be sent along with all requests made to our GraphQL server.
Posts are the heart of any blog. Users should be able to add a new post. Again, we’ll first create the GraphQL mutation for adding new posts to our blog. Add the code below to src/graphql.js
:
This mutation takes the title and content of a post we want to add to our GraphQL server.
Next, create an AddPost
component within the Admin
folder and paste the code below into it:
This component renders a form for adding new posts. It uses the ADD_POST_MUTATION
passing to it the necessary variables. Since Apollo client caches (in memory in our case) it queries, we need a way to update the cache whenever we perform mutation actions. Notice there is an update
function which we use to update the store by adding the newly added post to cache. First, we fetch the data from the cache matching our query (ALL_POSTS_QUERY
), then we add the new post to the allPosts
array. Lastly, we write the new data back to cache. Once the post is successfully added, we redirect to the list of posts (which we’ll create shortly).
Open src/router/index.js
, and add the code below to it:
Users should be able to add new posts now:
We’ll first create the GraphQL query by adding the code below to src/graphql.js
:
This GraphQL query fetches all posts from our GraphQL server.
Next, create a Posts
component within the Admin
folder and paste the code below into it:
We make use of the Menu
component created earlier. Then we define our data which will be populated once the data is gotten from our GraphQL server. Within the apollo
object, we add our GraphQL query to fetch all users. This makes use of the ALL_USERS_QUERY
we created above. It is important to note that, the name of our data (allUsers
in this case) must be the same name used in our GraphQL query (allUsers
in this case). Once allUsers
is populated with data from our GraphQL server, we display the users in a table by looping through the array of users. We also add a link to view each user details.
Open src/router/index.js
, and add the code below to it:
Now when we visit the /admin/posts
route, we should see a list of posts as in the image below:
The blog homepage will display a list of all posts created just like in the displaying posts section. In fact, the homepage will use the exact same GraphQL used in displaying posts. It is only the markup of the homepage that will be different. Create a Home
component inside src/components
and add the code below to it:
As we can see the JavaScript section is identical to that of Posts
component. Just different markup. We loop through the posts array and display the title of each post linked with their slug.
Open src/router/index.js
, and add the code below to it:
Visiting the /
route, we should see our blog homepage as in the image below:
The last thing to add is the ability to view a specific post. Add the code below to src/graphql.js
:
This query fetches a post by its slug. It takes the slug of the post to be fetched as an argument.
Next, create a SinglePost
component inside src/components
and add the code below to it:
We display the post title and its content and a link to go back to the homepage. The JavaScript section follows the implementation used in displaying user details. In this case, we get the post slug from the route params.
Open src/router/index.js
, and add the code below to it:
Note: This route should be the last route in the routes array.
We should be able to view a single post now:
In this tutorial, we have seen how to build a blog app with GraphQL, Apollo client, and VueJS. We also saw how to connect our frontend app to a GraphQL server.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!