Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Commit

Permalink
Construct fully qualified base href using request data.
Browse files Browse the repository at this point in the history
  • Loading branch information
superafroman committed Mar 8, 2019
1 parent 9540383 commit b8a95d2
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion runtime/src/server/middleware/get_page_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import cookie from 'cookie';
import devalue from 'devalue';
import fetch from 'node-fetch';
import URL from 'url';
import { TLSSocket } from 'tls';
import { IGNORE } from '../constants';
import { Manifest, Page, Props, Req, Res } from './types';
import { build_dir, dev, src_dir } from '@sapper/internal/manifest-server';
Expand Down Expand Up @@ -300,7 +301,7 @@ export function get_page_handler(
const nonce_attr = (res.locals && res.locals.nonce) ? ` nonce="${res.locals.nonce}"` : '';

const body = template()
.replace('%sapper.base%', () => `<base href="${req.baseUrl}/">`)
.replace('%sapper.base%', () => `<base href="${get_base_href(req)}">`)
.replace('%sapper.scripts%', () => `<script${nonce_attr}>${script}</script>`)
.replace('%sapper.html%', () => html)
.replace('%sapper.head%', () => `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`)
Expand Down Expand Up @@ -366,3 +367,20 @@ function escape_html(html: string) {

return html.replace(/["'&<>]/g, c => `&${chars[c]};`);
}

function get_base_href(req: Req) {
return `${get_protocol(req)}://${req.headers['host']}${req.baseUrl}`
}

function get_protocol(req: Req) {
const proto = (<TLSSocket>req.connection).encrypted
? 'https'
: 'http';

const header = req.headers['x-forwarded-proto'] || proto
const index = header.indexOf(',')

return index !== -1
? header.substring(0, index).trim()
: header.trim()
}

0 comments on commit b8a95d2

Please sign in to comment.