Thanks @muted pilot for helping me out in my last question about Login with server component.
Now I am able to store the tokens I need, idToken, personId into cookies or localStorage from the login-form client component. Next I redirect to /postings, which loads up my postings/page server component.
And that page component needs to get a fetch from another server component fetchPostings.
I'm able to set the cookies and localStorage, but unable to fetch the required tokens from page and send them into fetchPostings to make the next call.
I read that js-cookies would let me solve that, but the tokens are undefined, I tried cookies from next/headers, but got an error saying I can't do that.
Is there another way to pass those tokens after login into server components for another call?
The only other thing I can think of is while I'm in the login server component, to go ahead and make that getUserPostings call there, then passing everything into the login-form client component to pass on.
My postings/page (server component)
import Cookies from 'js-cookie';
// import { cookies } from 'next/headers';
import PostingsList from '@/components/postings/postings-list';
import fetchPostings from '@/services/postings';
export default async function Postings() {
let postingsData = [];
let errorMessage;
const cookies = new Cookies();
// const cookieStore = cookies();
const idToken = cookies.get('idToken') ?? '';
const personId = cookies.get('personId') ?? '';
// console.log('idToken', idToken);
// console.log('personId', personId);
try {
postingsData = await fetchPostings(idToken, personId);
console.log('postingsData', postingsData);
} catch (error: any) {
errorMessage = error.message;
}
return (
<>
<PostingsList postings={postingsData} errorMessage={errorMessage} />
</>
);
};
My fetchPostings (server component)
'user server';
import { API_GET_POSTINGS, METHOD_GET } from '@/constants';
const fetchPostings = async (idToken: string, personId: string) => {
const generateSearchParams = () => {
const params = new URLSearchParams();
params.append('posting-state', 'all');
params.append('page', '1');
params.append('page-size', '5');
return params;
};
const params = generateSearchParams();
try {
const response = await fetch(API_GET_POSTINGS(personId || '', params), {
...METHOD_GET,
headers: {
Authorization: idToken || '',
},
});
if (!response.ok) {
throw new Error(`Error fetching postings: ${response.statusText}`);
}
const data = await response.json();
console.log('fetching postings data:', data);
return data;
} catch (error: any) {
console.error(error);
return error;
}
};
export default fetchPostings;
my login-form (client component)
Where I save the cookies/localStorage
// ? store idToken in redux
if (idToken) {
cookies().set('idToken', idToken);
localStorage.setItem('idToken', idToken);
}