I need to get the pathname without using client-side rendering but I haven't found how to use the getServerSideProps function.
I first tried using usePathname but it turns the component into client-side. I need to keep it server-side
I need to get the pathname without using client-side rendering but I haven't found how to use the getServerSideProps function.
I first tried using usePathname but it turns the component into client-side. I need to keep it server-side
Based on the documentation, resolvedUrl
is one of the params of context
object in getServerSideProps
. You can use that in server-side and then pass it as a prop to the client-side. Here's an example that may help:
import { useRouter } from "next/router";
export async function getServerSideProps(context) {
const { resolvedUrl } = context;
// You can use the resolvedUrl here, e.g. parse the pathname
const pathname = new URL(resolvedUrl, "https://example.com").pathname;
return {
props: {
pathname,
},
};
}
function MyComponent({ pathname }) {
return <div>Pathname: {pathname}</div>;
}
export default MyComponent;