Monday 8 March 2021

How to server side redirect to other page without reloading the page and still keeping the url in Nextjs app?

I have a [slug].js page that will fetch API to get the destination page

export async function getServerSideProps({ query, res }) {
    const slug = query.slug;
    try {
        const destination = await RoutingAPI.matchSlug(slug);
        res.writeHead(302, { Location: destination });
        res.end();
        // return {
        //     redirect: {
        //         permanent: true,
        //         destination,
        //     },
        // }
    } catch (error) {
        return {
            notFound: true
        }
    }
}

If I client redirect from another page to slug page, it works and keeps URL the same as slug but it makes the browser reload. If I use

return {
     redirect: {
        permanent: true,
        destination,
     },
}

it will not reload the browser but it change URL to the destination, not the same as slug. How do i fix this problem? I would appreciate any ideas, thanks



from How to server side redirect to other page without reloading the page and still keeping the url in Nextjs app?

No comments:

Post a Comment