I've integrated the next-csrf library (https://github.com/j0lv3r4/next-csrf) into my next.js app to safeguard api routes.
Despite following the documentation, I'm encountering a 500 error with the following message:
{"message":"Signed cookie string must be provided."}
Below is the code snippet:
/lib/csrf.js
:
import { nextCsrf } from 'next-csrf';
const options = {
secret: `${process.env.CSRF_SECRET}`,
};
export const { csrf, csrfToken } = nextCsrf(options);
The page making the api call looks like this:
import { useState, useEffect } from 'react';
import axios from 'axios';
import { withRouter } from 'next/router';
import { Page, PostBlock } from '@/components';
const Main = ({ router, csrfToken }) => {
const [postsData, setPostsData] = useState({ posts: [], page: 0, pages: 0 });
function fetchData() {
axios
.get('/api/articles', {
headers: { 'XSRF-TOKEN': csrfToken },
params: {
page: router.query?.page,
lang: router.locale,
tag: router.query.tag,
},
})
.then(response => {
setPostsData(response.data);
})
.catch(error => console.log(error));
}
useEffect(() => {
fetchData();
}, []);
return (
<Page title='Home' className='home-template'>
<div id='grid' className='post-grid'>
{postsData.posts?.map(post => {=
return (
<PostBlock
featured={post.featured}
key={post.slug}
/>
);
})}
</div>
</Page>
);
};
export default withRouter(Main);
The token is functioning correctly as evidenced by the header in the network tab:
https://i.sstatic.net/bAkvu.png
For the api route section, the relevant code is as follows:
import { getPosts } from '../../../utils/index';
import { csrf } from '../../../lib/csrf';
function handler(req, res) {
const {
query: { page, lang, tag },
method,
} = req;
switch (method) {
case 'GET':
const posts = getPosts(page, lang, tag);
res.status(200).json(posts);
break;
default:
break;
}
}
export default csrf(handler);
Additionally, when attempting to make an api call using Postman, it works. Notably, there's a cookie with the "XSRF-TOKEN" value present despite not being explicitly set, posing uncertainty on its origin:
https://i.sstatic.net/Uovvs.png
What steps can I take to address this issue?