Next.js: Can't get protocol in server-side rendering

Created on 5 Jul 2017  路  6Comments  路  Source: vercel/next.js

Hi All!

My question is i need to get origin dynamically,
I try req.headers and I got:

image

Yes!, I got host, but I also need the protocol, which needs to concat with host to create new api path. I browsed All req properties but I got nothing. Have any good idea? thx a lot!

Most helpful comment

It's safe to assume it's always http and the SSL termination has to be done by a reverse proxy like Nginx. These set the X-Forwarded-Proto header which you could use.

All 6 comments

I think next use the express request so you should find it here: http://expressjs.com/fr/api.html#req.protocol

@quentin-sommer we don't use express. Just the plain http server build into node.js.

Well that's my bad!

@hank7444 I dug in the req object, it has _parsedOriginalUrl and _parsedUrl fields which are both of type Url. The structure is as follows:

{
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: null,
     pathname: '/page',
     path: '/page',
     href: '/page',
     _raw: '/page'
 }

I tested it only on localhost and as you see most of the fields are blank... I don't know if it's because I use a wrapper Expressjs server that calls next or if it's because of the localhost. Maybe you'll get what you want here. Be careful tho since _ prefixed fields are usually meant for private use

It's safe to assume it's always http and the SSL termination has to be done by a reverse proxy like Nginx. These set the X-Forwarded-Proto header which you could use.

I managed to do that with following line
const protocol = req.headers.referer.split('://')[0]

It looks dirty anyway

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

jesselee34 picture jesselee34  路  3Comments

wagerfield picture wagerfield  路  3Comments

kenji4569 picture kenji4569  路  3Comments

knipferrc picture knipferrc  路  3Comments