To set up JWT in httpOnly cookies in Strapi v4, you can follow these steps:
- Install the Nookies package in your frontend folder. Nookies is a third-party package that you can use to implement this functionality.
$ npm install nookies
- Update the
pages/index.jsfile:
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}`
}
});
- In your Strapi backend, you can create a custom endpoint to set the JWT in a secure httpOnly cookie. Here’s an example of how you can do this: