I have a domain on Namecheap that points to my Heroku instance via an ALIAS
.
ALIAS @ example.com
I have the automatic SSL certificate enabled on my Heroku instance.
Accessing http://example.com
and https://example.com
works.
However, I want to disallow HTTP navigation by enforcing HTTPS.
According to Heroku, that must be handle at application level.
How can I do this with SvelteKit?
You have to create a server hook, that intercept the request, analyze its URL and redirect to its HTTPS equivalent.
In src/hooks.server.ts
// Based on this environment variable, we will redirect or not. Useful to develop without SSL.
import { HTTPS_ENABLED } from '$env/static/private';
import type { Handle } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => {
// If enabled, we start processing the request's URL.
if (HTTPS_ENABLED === 'true') {
// As recommended by Heroku, we check the header 'X-Forwarded-Proto' they add on the fly,
// to verify the scheme of the original request.
const forwardedProto = event.request.headers.get('X-Forwarded-Proto');
// If either the original scheme or the one forwarded by Heroku is 'http', we redirect.
if (event.url.protocol === 'http:' || forwardedProto === 'http') {
// We parse the URL to replace whatever scheme set by 'https'.
const protoIndex = event.url.href.indexOf(':');
return new Response(null, {
status: 301,
headers: { location: 'https' + event.url.href.substring(protoIndex) }
});
}
}
return await resolve(event);
};