In this tutorial, we will learn about authentication (local authentication) in Strapi. We’ll create a simple blog app where authenticated users can create, read, and delete posts. In contrast, unauthenticated users can only view a list of posts but cannot read, create, or delete posts. We’ll have a login route, signup route, and a create post route where users can create posts from. We’ll also be working with Image uploads to see how users can upload images from the Nuxt.js frontend to our Strapi backend.
Here’s what we’ll be building:
Let’s get started!
The Strapi documentation says that Strapi is a flexible, open-source, headless CMS that gives developers the freedom to choose their favorite tools and frameworks and allows editors to manage and distribute their content easily. Strapi enables the world's largest companies to accelerate content delivery while building beautiful digital experiences by making the admin panel and API extensible through a plugin system.
Strapi helps us build an API quickly with no hassle of creating a server from scratch. With Strapi, we can do everything literally, and it’s easily customizable. We can add our code and edit functionalities easily. Strapi is amazing, and its capabilities would leave you stunned.
Strapi provides an admin panel to edit and create APIs. It also provides easily-editable code and uses JavaScript.
To install Strapi, head over to the Strapi documentation and run the following commands:
1 yarn create strapi-app my-project //using yarn
2 npx create-strapi-app@latest my-project //using npx
1Replace `my-project` with the name you wish to call your application directory. Your package manager will create a directory with the specified name and install Strapi.
If you followed the instructions correctly, you should have Strapi installed on your machine. Run the following command:
1 yarn develop //using yarn
2 npm run develop //using npm
To start our development server, Strapi starts our app on https://localhost:1337/admin.
We have Strapi up and running; the next step is to create our products content-type.
content-type
builder in the side menu.Collection-types
, click create new collection type
.User
(from users-permissions-user), and click on “user has many articles” relation.settings
on the side menu, and select Roles
under Users and Permissions Plugin
.Authenticated
and check all permissions.public
.find
and findOne
permissions.save
to save changes.author
with whatever credentials you’d like, but select the authenticated role and enable email confirmation.Users_permissions_user
as an author. This means that the user author
created the article.Save the content-types
. We can now view our API in JSON format when we visit https://localhost:1337/api/articles.
Now that we’ve created our Strapi API, we need to build our front end with Nuxt.js.
To install Nuxt.js, visit the Nuxt docs.
We want to use Nuxt in SSR mode and server hosting; we also want Tailwind CSS as our preferred CSS framework. Select those and whatever options you want for the rest. Preferably, leave out C.I, commit-linting, and style-linting.
1 yarn create nuxt-app <project-name> //using yarn
2 npx create-nuxt-app <project-name> //using npx
3 npm init nuxt-app <project-name> //using npm
It will ask you some questions (Name, Nuxt Options, UI Framework, TypeScript, Linter, Testing Framework, etc.).
Once all the questions are answered, the dependencies will be installed. The next step is to navigate to the project folder and launch it using the command below.
1 yarn dev //using yarn
2 npm run dev //using npm
We should have Nuxt running on https://localhost:3000.
We need to query our Strapi backend API, and Strapi provides a great package. We could use Nuxt’s native @nuxtjs/http module or axios to query our API, but @nuxtjs/strapi makes it easier. To install @nuxtjs/strapi:
1 yarn add @nuxtjs/strapi@^0.3.4 //using yarn
2 npm install @nuxtjs/strapi@^0.3.4 //using npm
nuxt.config.js
file and add the following code to the file.1 modules: [
2 // ...other modules
3 '@nuxtjs/strapi',
4 ]
5
6 strapi: {
7 url: process.env.STRAPI_URL || `https:localhost:1337/api`,
8 entities: ['articles'],
9 }
We can now use @nuxtjs/strapi to make API calls and continue building our pages and components.
The @nuxtjs/strapi documentation can be found here.
1this.$strapi() //from properties such as methods, data, computed
2
3$strapi() //from nuxtjs lifecycle methods
Strapi rich text gives us the privilege of writing markdown in our content. In order to parse the markdown content from the backend, we need to install the @nuxtjs/markdownit package.
1 yarn add @nuxtjs/markdownit //using yarn
2 npm install @nuxtjs/markdownit //using npm
1 modules: [
2 //...other modules
3 '@nuxtjs/markdownit'
4 ],
5
6 markdownit: {
7 preset: 'default',
8 linkify: true,
9 breaks: true,
10 injected: true,
11 // use: ['markdown-it-div', 'markdown-it-attrs'],
12 },
Now, we can use @nuxtjs/markdownit to parse our markdown content. The @nuxtjs/markdownit documentation can be found here.
We can proceed with building the user-interface of our blog app.
To Build the Signup Page:
signup.vue
file in the pages directory.1 cd pages
2 touch signup.vue
Fill signup.vue with the following lines of code.
1 <template>
2 <div class="w-4/5 mx-auto md:w-1/2 text-center my-12">
3 <div v-show="error !== ''" class="p-3 border">
4 <p>{{ error }}</p>
5 </div>
6 <h1 class="font-bold text-2xl md:text-4xl mt-5">Signup</h1>
7 <form @submit="createUser">
8 <div>
9 <input
10 v-model="email"
11 class="p-3 my-5 border w-full"
12 type="email"
13 placeholder="email"
14 />
15 </div>
16 <div>
17 <input
18 v-model="username"
19 class="p-3 my-5 border w-full"
20 type="text"
21 placeholder="username"
22 />
23 </div>
24 <div>
25 <input
26 v-model="password"
27 class="p-3 my-5 border w-full"
28 type="password"
29 placeholder="password"
30 />
31 </div>
32 <div>
33 <button
34 class="button--green"
35 :disabled="email === '' || password === '' || username === ''"
36 type="submit"
37 >
38 Signup
39 </button>
40 </div>
41 </form>
42 </div>
43 </template>
44 <script>
45 export default {
46 data() {
47 return {
48 email: '',
49 username: '',
50 password: '',
51 error: '',
52 }
53 },
54 methods: {
55 async createUser(e) {
56 e.preventDefault()
57 try {
58 const newUser = await this.$strapi.register({
59 email: this.email,
60 username: this.username,
61 password: this.password,
62 })
63 console.log(newUser)
64 if (newUser !== null) {
65 this.error = ''
66 this.$nuxt.$router.push('/articles')
67 }
68 } catch (error) {
69 this.error = error.message
70 }
71 },
72 },
73 middleware: 'authenticated',
74 }
75 </script>
76 <style></style>
1We just built our signup logic; when users provide their email, username and password, and click the signup button, we invoke the `createUser` method. All we’re doing in this method is registering a new user using the `@nuxtjs/strapi` module i.e `this.$strapi.register()` method. Then, we redirect the user to the `/articles` route. If the email belongs to an existing user, an error message is displayed at the top of the page. Finally, we’re using `nuxtjs middleware` feature to invoke a custom-made `middleware` that we’re going to create.
2
3**To Build the Login Page**
4
5- Execute the following lines of code to create a `login.vue` file in the pages directory.
6
7```vue
8 touch login.vue
1 <template>
2 <div class="w-4/5 mx-auto md:w-1/2 text-center my-12">
3 <div v-show="error !== ''" class="p-3 border">
4 <p>{{ error }}</p>
5 </div>
6 <h1 class="font-bold text-2xl md:text-4xl mt-5">Login</h1>
7 <form @submit="loginUser">
8 <div>
9 <input
10 v-model="identifier"
11 class="p-3 my-5 border w-full"
12 type="email"
13 placeholder="email"
14 />
15 </div>
16 <div>
17 <input
18 v-model="password"
19 class="p-3 my-5 border w-full"
20 type="password"
21 placeholder="password"
22 />
23 </div>
24 <div>
25 <button
26 :disabled="identifier === '' || password === ''"
27 class="button--green"
28 type="submit"
29 >
30 Login
31 </button>
32 </div>
33 </form>
34 </div>
35 </template>
36 <script>
37 export default {
38 data() {
39 return {
40 identifier: '',
41 password: '',
42 error: '',
43 }
44 },
45 methods: {
46 async loginUser(e) {
47 e.preventDefault()
48 try {
49 const user = await this.$strapi.login({
50 identifier: this.identifier,
51 password: this.password,
52 })
53 console.log(user)
54 if (user !== null) {
55 this.error = ''
56 this.$nuxt.$router.push('/articles')
57 }
58 } catch (error) {
59 this.error = 'Error in login credentials'
60 }
61 },
62 },
63 middleware: 'authenticated',
64 }
65 </script>
66 <style></style>
We’ve just built our login logic; users provide a unique identifier (email) and password, then click on the login button, which calls the loginUser method. This method attempts to log the user in using the @nuxtjs/strapi module i.e this.$strapi.login() method and returns a user object if a user is found or an error if the credentials are invalid. The user is redirected to the /article
route if the process was successful and an error message is displayed if an error occurred.
To Create an Authenticated Middleware
Let’s create our middleware function:
1 cd middleware
2 touch authenticated.js
1 export default function ({ $strapi, redirect }) {
2 if ($strapi.user) {
3 redirect('/articles')
4 }
5 }
What we have done is set up a middleware that checks if a user is logged in or not. If a user is logged in, we redirect them to the /articles
page, this middleware is useful for preventing a logged in user from accessing the Login, Signup and ‘/’ route. We don’t want to have a logged in user signing up on our app for whatsoever reason.
To Build the Nav Component
Nav.vue
file in the components directory.1 cd components
2 touch Nav.vue
1 <template>
2 <div
3 class="flex space-x-5 items-center justify-center bg-black text-white py-3 sm:py-5"
4 >
5 <NuxtLink to="/articles">Articles</NuxtLink>
6 <div v-if="$strapi.user === null">
7 <NuxtLink class="border-r px-3" to="/login">Login</NuxtLink>
8 <NuxtLink class="border-r px-3" to="/signup">Signup</NuxtLink>
9 </div>
10 <div v-if="$strapi.user !== null">
11 <span class="border-r px-3">{{ $strapi.user.username }}</span>
12 <NuxtLink class="border-r px-3" to="/new">Create Post</NuxtLink>
13 <button class="pl-3" @click="logout">Logout</button>
14 </div>
15 </div>
16 </template>
17 <script>
18 export default {
19 name: 'Nav',
20 methods: {
21 async logout() {
22 await this.$strapi.logout()
23 this.$nuxt.$router.push('/')
24 },
25 },
26 }
27 </script>
28 <style></style>
In the Nav component, all we’re doing is building a navigation bar for our application. Using the @nuxt/strapi module, we’re checking if there is no logged in user, then we display signup and login optiona in the nav bar. But if a user is logged in, we display their username, logout option and a “create post” link.
Note:
1 $strapi.user //returns the loggedin user or null
When a user clicks the logout button, we invoke a logout function, which in turn invokes the $strapi.logout()
function that logs the user out. Then, we redirect the user to the '``/``'
route using the $nuxt.$router.push()
method.
To Build the Homepage
index.vue
file in the pages directory.1 cd pages
2 code index.vue
1 <template>
2 <div class="container">
3 <div>
4 <h1 class="title">Welcome To The BlogApp</h1>
5 <div class="links">
6 <NuxtLink to="/login" class="button--green"> Login </NuxtLink>
7 <NuxtLink to="/articles" class="button--grey"> Continue Free </NuxtLink>
8 </div>
9 </div>
10 </div>
11 </template>
12 <script>
13 export default {
14 middleware: 'authenticated',
15 }
16 </script>
17 <style>
18 /* Sample `apply` at-rules with Tailwind CSS
19 .container {
20 @apply min-h-screen flex justify-center items-center text-center mx-auto;
21 }
22 */
23 .container {
24 margin: 0 auto;
25 min-height: 100vh;
26 display: flex;
27 justify-content: center;
28 align-items: center;
29 text-align: center;
30 }
31 .title {
32 font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
33 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
34 display: block;
35 font-weight: 300;
36 font-size: 80px;
37 color: #35495e;
38 letter-spacing: 1px;
39 }
40 .subtitle {
41 font-weight: 300;
42 font-size: 42px;
43 color: #526488;
44 word-spacing: 5px;
45 padding-bottom: 15px;
46 }
47 .links {
48 padding-top: 15px;
49 }
50 </style>
What we have here is our homepage. We’re using Nuxt.js middleware feature to invoke a custom-made middleware that we created.
To Build the Articles Page
1 cd pages
2 touch articles.vue
1 <template>
2 <div>
3 <Nav class="mx-auto sticky top-0" />
4 <h1 class="text-center my-5">All our articles</h1>
5 <div
6 v-show="error !== ''"
7 class="sticky z-100 border p-5 m-3 top-0 bg-black text-white text-center mx-auto w-4/5 sm:w-4/5 md:w-4/5 lg:w-1/2"
8 >
9 <p class="m-1 sm:m-3">{{ error }}</p>
10 <button class="button--grey" @click="resetError()">Ok</button>
11 </div>
12 <div
13 v-for="(article, i) in data.data"
14 :key="i"
15 class="sm:flex sm:space-x-5 my-5 shadow-lg mx-auto w-4/5 sm:w-4/5 md:w-4/5 lg:w-1/2"
16 >
17 <img
18 :src="`https://localhost:1337${article.attributes.Image.data.attributes.formats.small.url}`"
19 class="max-h-screen sm:h-48"
20 />
21 <div class="px-2 sm:pr-2 sm:text-left text-center">
22 <h3 class="font-bold my-3">{{ article.attributes.name }}</h3>
23 <p class="my-3">{{ article.attributes.description }}</p>
24 <button class="button--green mb-4 sm:mb-0" @click="readPost(article)">
25 Read more
26 </button>
27 </div>
28 </div>
29 </div>
30 </template>
31 <script>
32 export default {
33 async asyncData({ $strapi, $md }) {
34 const data = await $strapi.$articles.find({ populate: '*' })
35 return { data }
36 },
37 data() {
38 return {
39 error: '',
40 }
41 },
42 methods: {
43 readPost(article) {
44 if (this.$strapi.user) {
45 this.error = ''
46 this.$nuxt.$router.push(`/article/${article.id}`)
47 } else {
48 this.error = 'Please Login to read articles'
49 }
50 },
51 resetError() {
52 this.error = ''
53 },
54 },
55 }
56 </script>
57 <style></style>
First, we’ll use the @nuxtjs/strapi module to find all our articles. Then, we’ll display the articles on our page. In the readPost
method, we’re checking if a user is logged in before allowing the user to read a post. If the user is not logged in, we display an error message saying “Please, log in to read articles.”
To Build the Article Content Page
1 mkdir article
2 touch _id.vue
1 <template>
2 <div>
3 <Nav class="mx-auto sticky top-0" />
4 <div class="w-4/5 sm:w-1/2 mx-auto my-5">
5 <h3 class="my-5 font-bold text-4xl">
6 {{ article.name }}
7 </h3>
8 <img
9 :src="`https://localhost:1337${article.Image.url}`"
10 class="max-h-screen"
11 />
12 <p class="mt-5 font-bold">
13 written by {{ article.users_permissions_user.username }}
14 </p>
15 <div class="my-5" v-html="$md.render(article.content)"></div>
16 <button
17 v-if="
18 $strapi.user && article.users_permissions_user.id === $strapi.user.id
19 "
20 class="button--grey"
21 @click="deletePost(article.id)"
22 >
23 Delete
24 </button>
25 </div>
26 </div>
27 </template>
28 <script>
29 export default {
30 async asyncData({ $strapi, route }) {
31 const id = route.params.id
32 const article = await $strapi.$articles.findOne(id, {
33 populate: '*',
34 })
35 return { article }
36 },
37 methods: {
38 async deletePost(id) {
39 await this.$strapi.$articles.delete(id)
40 this.$nuxt.$router.push('/articles')
41 },
42 },
43 middleware({ $strapi, redirect }) {
44 if ($strapi.user === null) {
45 redirect('/articles')
46 }
47 },
48 }
49 </script>
50 <style scoped>
51 h1 {
52 font-weight: 700;
53 font-size: 2rem;
54 margin: 0.5em 0;
55 }
56 </style>
On this page, we’re displaying an individual article with its complete content using markdownit i.e $md.render(article.content)
, author name, and more. We’ll also display a delete button if the current user is the author of the post; we’ll check for that by using the @nuxtjs/strapi
module. We don’t want an unauthorized user to delete a post they didn’t create. Finally, in the middleware, we’re checking for a logged in user; if there’s none, we’ll redirect to the ‘/articles’ route, making sure the article content page is totally inaccessible to unauthenticated users.
NOTE:
The Users_permissions
plugin is currently broken, but we can populate the users_permissions_user
field manually from the Strapi backend. Follow the steps below to do so:
src/api/controllers
folder.article.js
file.1 'use strict';
2 /**
3 * article controller
4 */
5 const { createCoreController } = require('@strapi/strapi').factories;
6
7
8 module.exports = createCoreController('api::article.article', ({ strapi }) => ({
9 async findOne(ctx) {
10 console.log(ctx.request.params.id)
11 const data = await strapi.service('api::article.article').findOne(ctx.request.params.id, {
12 populate: ['Image', 'users_permissions_user']
13 })
14 delete data.users_permissions_user.password
15 return data
16 }
17 }));
What have manually populated the Image
and users_permission_user
fields. Then, we’ll delete the password so that it is not passed along in the response to the client.
To Build the Create Article Page
New.vue
file in the pages directory.1 touch New.vue
1 <template>
2 <div class="w-4/5 mx-auto md:w-1/2 text-center my-12 overflow-hidden">
3 <form ref="form" @submit="createPost">
4 <h2 class="font-bold text-2xl md:text-4xl mt-5">Create a new post</h2>
5 <div>
6 <input
7 v-model="form.name"
8 name="Title"
9 type="text"
10 placeholder="title"
11 class="p-3 my-3 border w-full"
12 />
13 </div>
14 <div>
15 <input
16 v-model="form.description"
17 name="description"
18 type="text"
19 placeholder="description"
20 class="p-3 my-3 border w-full"
21 />
22 </div>
23 <div>
24 <textarea
25 v-model="form.content"
26 name="Content"
27 cols="30"
28 rows="10"
29 class="p-3 my-3 border w-full"
30 ></textarea>
31 </div>
32 <div>
33 <input
34 type="file"
35 name="Image"
36 class="p-3 my-3 border w-full"
37 @change="assignFileInput()"
38 />
39 </div>
40 <div>
41 <button
42 class="button--green"
43 :disabled="
44 form.name === '' ||
45 form.description === '' ||
46 form.content === '' ||
47 fileInput === ''
48 "
49 type="submit"
50 >
51 Create
52 </button>
53 </div>
54 </form>
55 </div>
56 </template>
57 <script>
58 export default {
59 data() {
60 return {
61 form: {
62 name: '',
63 description: '',
64 content: '',
65 users_permissions_user: this.$strapi.user.id,
66 },
67 fileInput: '',
68 }
69 },
70 methods: {
71 async createPost(e) {
72 const formData = new FormData()
73 let file
74 const formElements = this.$refs.form.elements
75 formElements.forEach((el, i) => {
76 if (el.type === 'file') {
77 file = el.files[0]
78 }
79 })
80 formData.append(`files.Image`, file, file.name)
81 formData.append('data', JSON.stringify(this.form))
82 e.preventDefault()
83 await this.$strapi.$articles.create(formData)
84 this.$nuxt.$router.push('/articles')
85 },
86 assignFileInput() {
87 const formElements = this.$refs.form.elements
88 formElements.forEach((el, i) => {
89 if (el.type === 'file') {
90 this.fileInput = el.files[0] !== undefined ? el.files[0].name : ''
91 }
92 })
93 },
94 },
95 middleware({ $strapi, redirect }) {
96 if (!$strapi.user) {
97 redirect('/articles')
98 }
99 },
100 }
101 </script>
102 <style></style>
We just created the logic to enable authenticated users to create new articles. The logic is complicated, especially the file upload logic, so let’s work through it step by step.
We built a content creation form as usual, with fields for title, description, image upload and content, and the create button.
fileInput
. Next, the createPost()
method allows users create articles.
FormData
we append the form object from the page’s data property in string form to FormData
with a data property. files.image
property. This is because, for multipart data, Strapi requires that the property be preceded by files i.e files.${fieldname}
and our fieldname from the article content-type is image.With all that done, we should have our create article logic working fine.
The frontend repo for this tutorial can be found here The backend repo for this tutorial can be found here. We’ve come to the end of this tutorial. By now, you have what it takes to tackle Strapi authentication with NuxtJs in your arsenal.
Alexander Godwin is a Software Developer and writer that likes to write code and build things. Learning by doing is the best way and it's how Alex helps others learn. Follow him on Twitter (@oviecodes)