Search code examples
authenticationdevopsstrapi

Automatically Generating API Token in Strapi for Development


I'm currently working on a project using Strapi and Nextjs (they are seperated from each other), and I'm trying to streamline our development process by automatically obtaining an authentication token. This would help me avoid repetitive manual steps during development: opening the Strapi web interface, creating an API token and exporting it as an env var for my Nextjs app.

Do you guys have a cool solution for this?

I tried creating a Nodejs script to generate an admin user and save an api token in the strapi database. But not I am not sure if this is the way.


Solution

  • You can do this to apply a token on Strapi v4:

    const tokenService = strapi.service('admin::api-token');
    
    const attributes = {
        name: `token${getRandomID()}`,
        description: '',
        type: 'full-access',
        lifespan: null,
        // type: "custom",
        // permissions: [
        //    "api::restaurant.restaurant.find",
        // ]
    };
    
    const apiToken = await tokenService.create(attributes);
    

    reference: https://forum.strapi.io/t/v4-unit-testing/14818/34?page=2