How to get user agent on load function in SvelteKit

Viewed 2510

I want to get the user agent on the load function to choose whether to perform server-side rendering or not depending on the visitor is googlebot or not.

How can I access it inside the load function?

I'm using the latest version of SvelteKit which is 1.0.0.

1 Answers

Managed it using hooks.

Create hooks.js inside src folder:

export function getSession(request) {
    return {
        userAgent: request.headers['user-agent']
    }
}

Then you can use it inside load function of each component you want:

<script context="module">
    export async function load({ session }) {
        console.log(session.userAgent)
    }
</script>

See hooks section for more information in docs.

Related