Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getServerSideProps access current browser url

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?

like image 297
doorman Avatar asked Feb 16 '26 20:02

doorman


2 Answers

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.

like image 126
juliomalves Avatar answered Feb 20 '26 04:02

juliomalves


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

}
like image 20
Arian Nargesi Avatar answered Feb 20 '26 03:02

Arian Nargesi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!