🍝 Cooking a Deliveroo clone with Nuxt (Vue.js), GraphQL, Strapi and Stripe - πŸ” Authentication (part 4/7)

Tutorial illustration

This tutorial is part of the Β« Cooking a Deliveroo clone with Nuxt (Vue.js), GraphQL, Strapi and Stripe Β»:

Note: the source code is available on GitHub: https://github.com/strapi/strapi-examples/tree/master/nuxt-strapi-deliveroo-clone-tutorial.

πŸ” Authentication

At this point, you may have expected to get ready to order. But before that, we need to give the user the possibility to register and login to our app. No worries, Strapi comes to the rescue with its Users & Permissions plugin already installed in your project.

Authentication

Auth store

As you may imagine, we need a store dedicated to the authentication:

Path: store/auth.js

Why cookies? πŸͺ

Nothing related to this food tutorial...

Most of the time, progressive web apps store a JSON Web Token (JWT) in the local storage. That works pretty well, and this is what the Strapi JavaScript SDK does by default (it also stores it as a cookie).

The fact is that we would like to display the username in the header (coming later in this tutorial). So we need to store it somewhere.

We could have store it in the local storage, but since Nuxt supports server-side rendering, which has not access to the local storage, we need to store it in the cookies.

For that reason, you have to install js-cookie:

npm i js-cookie  

Register

Create a new file named signup.vue in the pages directory, with the following content:

Path: pages/signup.vue

In this page, we insert a form which has three inputs: username, email and address. We also define a method named handleSubmit which uses the Strapi SDK to register the user before redirecting him to the home page.

Create a new user from this new page: http://localhost:3000/signup.

Logout

The user must be able to logout, ideally from a button in the header.

Add a logout mutation and a username setter in the auth store:

Path: store/auth.js

Path: components/Header.vue

Try to reload the page and you will see that nothing change: you still see the signin and signup links although you registered a user a few minutes ago. That happens because we do not use the auth/setUser mutation on the load page. Since Nuxt is rendered server side, we need to do a little trick using the nuxtServerInit action which is invoked when the Nuxt server starts:

Install cookieparser:

npm i cookieparser  

Path: store/index.js

Login

For the login view, we are going to do something really similar to the signup view:

Path: pages/signin.vue

That's it for the authentication!

πŸ›’ In the next section, you will learn how to create a full featured shopping card: https://blog.strapi.io/cooking-a-deliveroo-clone-with-nuxt-vue-js-graphql-strapi-and-stripe-shopping-card-part-5-7.