Implementing Authenticated API Requests to Strapi

Why Authenticate Requests?

Tutorial Requirements

Setting up Strapi

$ mkdir authenticated_requests && cd authenticated_requests
$ npx create-strapi-app@latest backend --quickstart
$ cd backend$ npm run develop

Setting up Next.js

$ npx create-next-app@latest frontend --use-npm
$ cd frontend$ npm run dev
export default function Home() {    return (        <div>            <h1>Implementing Authenticated API Requests to Strapi</h1>        </div>    );}

Implementing Authenticated Requests

export default function Home({ posts }) {    console.log(posts);    return (        <div>            <h1>Implementing Authenticated API Requests to Strapi</h1>        </div>    );}export async function getServerSideProps(ctx) {    // get posts from strapi REST API    const res = await fetch('http://localhost:1337/api/posts');    let posts = await res.json();    return {        props: {            posts: posts,        },    };}

Step 1: Create a New User

Step 2: Setting Roles

Step 3: Sending Authenticated Request

export default function Home({ posts, loginResponseData }) {    console.log(posts);    console.log(loginResponseData);    return (        <div>          <h1>Implementing Authenticated API Requests to Strapi</h1>          {posts && posts.map((_post_) => (            <div _key_={post.id}>              <h3>{post.attributes.title}</h3>            </div>          ))}      </div>    );}export async function getServerSideProps(ctx) {    const loginData = {        identifier: '<User Email>',        password: '<User Password>',    };    const login = await fetch(`http://localhost:1337/api/auth/local`, {        method: 'POST',        headers: {            Accept: 'application/json',            'Content-Type': 'application/json',        },        body: JSON.stringify(loginData),    });    const loginResponseData = await login.json();    // get posts from strapi REST API    const res = await fetch(`http://localhost:1337/api/posts`);    let posts = await res.json();    posts = posts.data    return {        props: {            posts: posts,            loginResponseData: loginResponseData,        },    };}
...const res = await fetch(`http://localhost:1337/api/posts`, {    headers: {      Authorization: `Bearer ${loginResponseData.jwt}`    }  });...

Step 4: Storing JWT with Nookies

$ npm install nookies
import { parseCookies, setCookie }  from 'nookies'export default function Home({posts}) {  return (    <div>          <h1>Implementing Authenticated API Requests to Strapi</h1>          {posts && posts.map((_post_) => (            <div _key_={post.id}>              <h3>{post.attributes.title}</h3>            </div>          ))}      </div>  )}export async function getServerSideProps(ctx) {  const jwt = parseCookies(ctx).jwt  // if there is a jwt token don’t authenticate the user again  if (jwt) {    // get posts from strapi REST API  const res = await fetch(`http://localhost:1337/api/posts`, {    headers: {      Authorization: `Bearer ${jwt}`    }  });  let posts = await res.json();  posts = posts.data  return {    props: {        posts:posts          }  }} // if there isn’t a jwt token authenticate the user     const loginData = {       identifier: '<User Email>',       password: '<User Password>',    }    const login = await fetch(`http://localhost:1337/api/auth/local`, {      method: "POST",      headers: {        'Accept': 'application/json',        'Content-Type': 'application/json'      },      body: JSON.stringify(loginData)    })    const loginResponseData = await login.json();    setCookie(ctx, 'jwt', loginResponseData.jwt, {      maxAge: 30 * 24 * 60 * 60,      path: '/',    })  // get posts from strapi REST API  const res = await fetch(`http://localhost:1337/api/posts`, {    headers: {      Authorization: `Bearer ${loginResponseData.jwt}`    }  });  let posts = await res.json();  posts = posts.data  return {    props: {        posts:posts          }  }}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Strapi

Strapi

The open source Headless CMS Front-End Developers love.