Home / Article Detail

Nextjs use getServerSideProps() the cookie is stored on the server side, used site-wide, and then jumps to page

📅 Nov 13, 2023✍️ lllomh

    Make it possible to jump to the success page on the server side. Instead of waiting for the front-end page to finish rendering before redirecting. 

    Better user experience.

    import { parse, serialize } from 'cookie';

    export async function getServerSideProps(context:GetServerSidePropsContext) {
    const cookies = parse(context.req.headers.cookie || '');
    const authState = cookies['U_S'] || 0;

    const {query} = context;
    const {obj} = query;


    // const objString = JSON.stringify(obj);
    if (obj && typeof obj === 'string') {
    context.res.setHeader('Set-Cookie', [
    serialize('U_S', obj, {path: '/', maxAge: 30 * 24 * 60 * 60}),
    serialize('U_TOKEN', JSON.parse(obj).token, {path: '/', maxAge: 30 * 24 * 60 * 60}),
    ]);

    // redirect to /index router
    return {
    redirect: {
    destination: '/',
    permanent: false,
    },
    };
    }


    try {
    const {get, post} = useRequest();
    const postData = {};
    const result = await post<{ code: string; data: any }>(P_PRODUCT_CATEGORY, postData);

    if (result.data.code === '00000') {
    const data = result.data.data;
    return {
    props: {
    authStates: authState,
    data,
    },
    };
    }
    } catch (error) {
    console.error('Error making POST request:', error);
    }

    return {
    props: {
    authStates: authState,
    data: [],
    },
    };
    }


    Use page router.