Node.js: identificare il browser in ExpressJS

In questo articolo vedremo come identificare un browser in ExpressJS.

Node.js di Gabriele Romanato

In questo articolo vedremo come identificare un browser in ExpressJS.

Il modulo NPM browser-detect può essere usato come middleware sfruttando la stringa contenuta nell'header HTTP User-Agent.

Quindi possiamo aggiungere una proprietà all'oggetto response.locals in modo da condividere le informazioni sul browser in tutte le view delle route su cui opera il middleware.

'use strict';

const express = require('express');
const router = express.Router();
const browser = require('browser-detect');


router.use((req, res, next) => {
    res.locals.browser = browser(req.headers['user-agent']);
    next();
});

router.get('/', (req, res, next) => {
    res.render('index');
});

module.exports = router;

Quindi nelle view possiamo ad esempio inserire il nome del browser tra i nomi delle classi CSS dell'elemento body.

<!DOCTYPE html>
<html lang="en">
<head>
<title>ExpressJS: browser detection</title>
<meta charset="UTF-8">
</head>
<body class="<%= browser.name %>">
</body>
</html>

In questo modo tale informazione potrà essere usata dal codice lato client.