DEV Community

Cover image for Strapi CMS Notes

Posted on • Updated on • Originally published at

Strapi CMS Notes

Install with postgres:

npx create-strapi-app backend
? Choose your default database client postgres
? Database name: strapi
? Host:
? Port: 5432
? Username: strapi
? Password: ******
? Enable SSL connection: No


NOTE: strapi handles users and administrators separately. Users will have access to your client side, where as administrators have access to the strapi-based backend as well. Administrators are users, but user's are not necessarily adminstrators.

Users are basically just a collection-type in strapi, that have some default permissions and roles applied for us out of the box. Users can be managed like any other collection-type, with all basic CRUD functionality available out of the box.

Users can also be blocked from the strapi admin panel, so if you ever need to revoke a user's access this can be done from the Blocked setting on the user's profile in the admin panel

Default Auth for Administrators:


POST ||  "\auth\login"                          => {token, user}
Enter fullscreen mode Exit fullscreen mode
// request.json

  "identifier": "",
  "password": "yourpassword"
Enter fullscreen mode Exit fullscreen mode



POST ||  "\auth\login\register"         => {token, user}
Enter fullscreen mode Exit fullscreen mode
// request.js

  "username": "yourusername",
  "email": "",
  "password": "yourpassword"
Enter fullscreen mode Exit fullscreen mode

JWT Access Token

In order to make authenticated requests, we'll need to grab the authToken that is returned from either the login or the registration endpoints and use that in order to populate our authorization header to send alongside our requests

 "Authorization": "Bearer <accessToken>"

Authenticated routes that do no have an authorization header or ones that provide invalid tokens, will fail with a 403 forbidden error.

Access Authenticated Routes

GET || http://localhost:1337/articles
Enter fullscreen mode Exit fullscreen mode


POST || http://localhost:1337/articles
Enter fullscreen mode Exit fullscreen mode
  "user": 1,
  "title": "This is the title of my article",
  "content": "This is some authenticated request content"
Enter fullscreen mode Exit fullscreen mode


Current User

We can also determine the user details of the current user, by hitting a specific endpoint generated by strapi:


GET || http://localhost:1337/users/me           => {user}
Enter fullscreen mode Exit fullscreen mode

Authentication Providers

Strapi provides several built-in authentication provider profiles, that we can simply generate an api key for. As an example we'll take a quick look at how to setup google as a strapi authentication provider.

NOTE: In order to use third party auth providers our strapi backend must be available to the web. For local development installations we can simply just use ngrok to provide us with an ssh tunnel that will expose our local environment for us.

./ngrok http 1337

This will spin up a local ngrok tunnel for our strapi application which is running on port 1337

ngrok by @inconshreveable                                                                                                                                        (Ctrl+C to quit)

Session Status                online                                                                                                                                             
Account                       Gaurang Shah (Plan: Free)                                                                                                                          
Version                       2.3.35                                                                                                                                             
Region                        United States (us)                                                                                                                                 
Web Interface                                                                                                                                     
Forwarding           -> http://localhost:1337                                                                                              
Forwarding           -> http://localhost:1337                                                                                             

Connections                   ttl     opn     rt1     rt5     p50     p90                                                                                                        
                              0       0       0.00    0.00    0.00    0.00  

Now if we were to navigate to: we will be able to access our local strapi install while ngrok is running.

Setup Google Authentication

  • [ ] Register a new project with google console

    • (click new project from project list dialog at the top)
  • [ ] Define project name (will be used to identify your project in google's console)

  • [ ] Setup OAuth Consent Screen (External = Open to Public Signup)

    • [ ] Add an application name
    • [ ] ⚠️ DO NOT add an application logo (this triggers google's approval process, we can avoid that by leaving it blank)
    • [ ] Add "Authorized Domains" (ngrok link w/ no protocol or trailing slash)
    • [ ] NOTE: Add links to homepage, privacy policy, and terms of service
    • [ ] SAVE
  • [ ] Generate OAuth Credentials

    • [ ] Click Create Credentials
    • [ ] Select OAuth Client ID
    • [ ] set Application Type : web application
    • [ ] assign a name (use the same as the project -- keep it simple)
    • [ ] Authorized Javascript Origins: (no trailing slash)
    • [ ] Authorized redirect URIs

    ⚠️ NOTE must use http with local ngrok tunnel

    callback used by google when a authentication request is triggered

    • [ ] SAVE
  • [ ] Save Credentials to Notes (Client ID, Client Secret)

Client ID :

Client Secret: sbh5eD4eydVjKMMkReU7Ss8K

Configure Strapi Google Auth Credentials

  • [ ] Enable Google as a provider
  • [ ] Add Client ID
  • [ ] Add Client Secret
  • [ ] prefix the redirectURL with our ngrok tunnel address



Connect To Google OAuth
Enter fullscreen mode Exit fullscreen mode


☝️ NOTE: When we navigate to the address above we get an 400 invalid_request error. This is because, Strapi uses a custom parameter called: strapi.config.server.url to determine the correct url where strapi is currently being served from.

Since we're running an ngrok tunnel strapi doesn't recognize that it is being tunneled into and so we get the invalid_request error, because the parameter never got set since we tunneled in.

To fix this we'll need to update our server settings and add the ngrok url so that strapi is aware of it:

// config/server.js

module.exports = ({env}) => ({
  /* ... */
  url: "",
  /* ... */

NOTE: be sure to leave off the trailing slash on the url

Now your changes should be reflected in your strapi console, when strapi restarts:

 Project information                                                          

│ Time               │ Mon Nov 02 2020 15:16:26 GMT-0500 (Eastern Stan… │
│ Launched in        │ 4480 ms                                          │
│ Environment        │ development                                      │
│ Process PID        │ 22312                                            │
│ Version            │ 3.2.4 (node v14.0.0)                             │
│ Edition            │ Community                                        │

 Actions available                                                            

Welcome back!
To manage your project 🚀, go to the administration panel at:

To access the server ⚡️, go to:

As we can see the url to our strapi installation now shows our ngrok url instead, so now we can try to connect to google's OAuth again:


Upon successful authentication we get a response with a token and information associated with the google user account.

NOTE: if user tries to use an email that is already registered thru another provider (i.e., strapi's built-in email provider) you will see another 400 error :

{"statusCode":400,"error":"Bad Request","message":[{"messages":[{"id":""}]}],"data":[{"messages":[{"id":""}]}]}

This is because the email already matches an existing user.

Now that we've successfully setup a 3rd party OAuth provider, we can now utitlize the token and information google provides back to us in our application. In order to do that we'll need to update our callback url, that we set in strapi and point to the url of the application where we want to consume this from:


WIth this in place you'll be able to make a GET request to the following endpoing from your application once a user has logged in to get their user details and jwt token from strapi:

GET || `${STRAPI_API_URL}/auth/google/callback?access_token=${access_token}`
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode


Creating Email Service

  • [ ] Install NodeMailer as Email Provider:
  npm i strapi-provider-email-nodemailer-v3
Enter fullscreen mode Exit fullscreen mode

other email providers


Configure Nodemailer as as strapi provider

// config/plugins.js

module.exports = ({ env }) => ({
  email: {
    provider: "nodemailer-v3",
    providerOptions: {},
    settings: {
      host: "process.env.SMTP_HOST",  
      port: 587,
      username: "process.env.EMAIL_ADDRESS",
      password: "process.env.EMAIL_PASSWORD",
      secure: false, // docs suggest keeping this as false when using port 587

Enter fullscreen mode Exit fullscreen mode

be sure to grab the config from your test email account, or use:

npx strapi generate:service <servicename>

npx strapi generate:service email
Enter fullscreen mode Exit fullscreen mode

This will create the following folder structure:

├── email
│   ├── documentation
│   └── services
Enter fullscreen mode Exit fullscreen mode

And this is the one file the command generates.

// api/email/services/email.js

'use strict';

 * `email` service.

module.exports = {
  // exampleService: (arg1, arg2) => {
  //   return isUserOnline(arg1, arg2);
  // }

Enter fullscreen mode Exit fullscreen mode

we'll update the service with our own logic

module.exports = {
  sendEmail: async(to, subject, html) => {
    // ☝️ creates logs for each email sent that show in the console"sendEmail: Sending Email")
    // ☝️ references the built-in email plugin to envoke it's send(fn)
    await strapi.plugins["email"]{
      // the basic configuration required by strapi's built-in email plugin
      from: process.env.EMAIL_ADDRESS,
      replyTo: process.env.EMAIL_ADDRESS,
    })"sendEmail: Email Sent")
Enter fullscreen mode Exit fullscreen mode

Set up Cron task for testing email implementation:

Next thing we'll need to do is enable strapi's cron task feature through our server, this will simply allow us to setup a cron job to test that the server is able to send emails

// config/server.js

module.exports = ({ env }) => ({
  host: env("HOST", ""),
  port:"PORT", 1337),

  cron: { enabled: true }, // enables all cron tasks

  admin: {
    auth: {
      secret: env("ADMIN_JWT_SECRET", "1f2afe006aac41e4ed791f66babcc874"),
    host: "",
    port: 3000, // --watch-admin

Now we can setup our cron task:

  '0 * * * * *': async () => {
    return await
      "Test Subject Line",
      "<div class"test">Test Context</div>" // include string or html

*❗️ NOTE: * the asterisks mean that this task will run every second. to stop the task use the commented setting. Specifying 0seconds means it will run once every minute instead. (basically when the seconds reset back to zero after 0:59).


Policies are functions which have the ability to execute specific logic on each request before it reaches the controller's action. They are mostly used for securing business logic easily. Each route of the project can be associated to an array of policies

For example, you can create a policy named isAdmin, which obviously checks that the request is sent by an admin user, and use it for critical routes.

Hey everyone, I'm Gaurang, a full-stack developer that is constantly learning and building in public. I love that I was able to change my career at such a late stage in life all by learning online with so many different resources. I generate content to reinforce what I'm learning and to help others like me in the future.

If you enjoyed my content, please feel free to connect with me wherever you spend your time online.

Top comments (0)