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

Construct absolute base href using request data. #600

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}