1
votes

I need to detect user device (browser, os, etc.) and show different navigation according to the device type (mobile or desktop). It should work during SSR in Sapper/Svelte.

Any help with it is very appreciated!

2
First of all, I've found this from Rich Harris: github.com/sveltejs/sapper/issues/552 - Anton G
Please use the edit link to update your post. All relevant information should be in the post itself, potential helpers should not have to read through the comments. - Gino Mempin
Thank you for the advice. I will do it. - Anton G

2 Answers

3
votes

For Sapper server.js:

polka() // You can also use Express
    .use(
        compression({ threshold: 0 }),
        sirv('static', { dev }),
        sapper.middleware({
            // let make device detection possibility, e.g. in <Nav> component
            session: (req, res) => ({
                'user-agent': req.headers['user-agent']
            })
        })
    )
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });

For Sapper Nav.svelte component

<script>
    export let segment;

    import { stores } from '@sapper/app';
    import UAParser  from 'ua-parser-js';

    // session is passed in server.js
    const { preloading, page, session } = stores();
    var parser = new UAParser();
    parser.setUA($session['user-agent']);

    let mobile = parser.getResult().device['type'] == 'mobile';

</script>

{#if mobile}
    <p>Mobile menu here</p>
{:else}
    <p>Desktop menu here</p>
{/if}

Also, don't forget to make npm install ua-parser-js --save first!

0
votes

have a look at tailwind css, it fits well with the class usage of svelte: https://tailwindcss.com/docs/responsive-design/

There are also examples using rollup to integrate with sapper: https://github.com/langbamit/sapper-postcss-tailwind-rollup