Handling authentication with Nuxt.js & graphql with Cookies (no localStorage)

Hassane Sow
2 min readJan 17, 2021

Hi welcome,

It’s been over a year now of working with Nuxt.js and graphQL but it’s only recently I’ve found out a way of saving user’s JWT token inside cookies with the server middleware option of Nuxt.js.

If you don’t know what the server middleware is, I strongly suggest you to see it in the Nuxt.js’s documentation but it’s just a way of binding an api or running a server within our Nuxt.js application.

We won’t build a graphQL api from scratch for this article, I assume you already have an API that generates JWT tokens for the authentication and a basic Nuxt.js app running.

The principle is very basic, we will build a simple API within our Nuxt.js, when we get back the authentication token from the GraphQl API we will make a request to the Nuxt.js API which will write the token inside the request cookies with the http only option set to true.

Let’s install Express.js & Cookie parser

The internal Nuxt.js API will be built with express.js, you can build it with wathever framework you want, it is a normal server that we are calling. The cookie parser will be used as a middleware to help us handling the cookies.

npm install express cookie-parser — save

After express is installed, create a directory in the root directory of your project and inside it add a index.js file which will contain the API.

We are just basically creating a post route that will contain the token inside its body, we get the token and add it in the cookies. You can add your security options and any other good practice you want, as I said above, it’s a normal api that we can call with the fetch api or axios.

To access the api we will nede to add it inside the serverMiddleware array inside the nuxt.config.js file.

Then in our Login.vue, we can now call the method in charge of authenticating the user, in this case, we will call it onLogin .

After calling the method, you can open the Developer tools and the storage part of it. Here you’ll see in the cookies a session object and you can recognize the token we set and the HttpOnly option set to true.

You can access it as you want and send it to your graphQL server for authentication or to get refresh tokens via the Nuxt.js context’s req object or by getting from the nuxtServerInit function of your store.

I hope this article was helpful for you, thank you for reading

--

--