doorman
doorman

Reputation: 16949

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?

Upvotes: 12

Views: 19255

Answers (2)

Arian Nargesi
Arian Nargesi

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

juliomalves
juliomalves

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

Related Questions