Reputation: 16949
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?
Upvotes: 12
Views: 19255
Reputation: 551
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
}
Upvotes: 3
Reputation: 50268
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/data
prefix 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.
Upvotes: 31