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!
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!
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!
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