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
To achieve a redirect from a [slug].js page without reloading the browser and keeping the URL the same as the slug, you can use the replace method of the Router object provided by Next.js instead of using server-side redirection. Here's an example:
import { useRouter } from 'next/router'; import { useEffect } from 'react'; import RoutingAPI from 'path/to/routing/api'; export default function SlugPage() { const router = useRouter(); const { slug } = router.query; useEffect(async () => { try { const destination = await RoutingAPI.matchSlug(slug); router.replace(destination); } catch (error) { // Handle error } }, [slug]); return ( // Your page content here ); }
In this example, the useEffect hook is used to fetch the destination URL from the API and redirect to it using the replace method of the router object. The useEffect hook has a dependency on the slug parameter provided by the router, so it will be re-executed whenever the slug changes.
Using router.replace instead of server-side redirection will allow you to perform the redirection without reloading the browser and keeping the URL the same as the slug. Note that this approach requires client-side JavaScript to execute the redirection, so it may not be suitable for all scenarios.