I am calling getServerSideProps and passing in the req and res parameters like this:
export async function getServerSideProps({ req, res }) {}
I need to get the current browser url path and I can't find it in the request object. Is there a way to get the current url inside getServerSideProps?
You can use the resolvedUrl field from the context parameter.
export async function getServerSideProps({ req, res, resolvedUrl }) {
console.log(resolvedUrl)
// Remaining code
}
From the getServerSideProps documentation:
resolvedUrl: A normalized version of the request URL that strips the_next/dataprefix for client transitions and includes original query values.
Note that resolvedUrl will not return the domain part of the URL, only the path and query string are returned.
You can have access to domain name via headers object in incoming request
// localhost:3000
context.req.headers.host
If you want the rest of the path, you can have it in url property in incoming request object
//blog/3
context.req.url
Full example:
export function getServerSideProps (context){
// localhost:3000
const domain = context.req.headers.host
// /blog/3
const path = context.req.url
//localhost:3000/blob/3
const fullAddress = domain + path
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With