Skip to content

Commit 263a4da

Browse files
authored
Parse UA (#203)
1 parent c4c34bd commit 263a4da

File tree

3 files changed

+45
-6
lines changed

3 files changed

+45
-6
lines changed

edge-functions/user-agent-based-rendering/package-lock.json

Lines changed: 36 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

edge-functions/user-agent-based-rendering/package.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
"@vercel/examples-ui": "^0.2.6",
1414
"next": "^12.1.0",
1515
"react": "17.0.2",
16-
"react-dom": "17.0.2"
16+
"react-dom": "17.0.2",
17+
"ua-parser-js": "^1.0.2"
1718
},
1819
"devDependencies": {
20+
"@types/ua-parser-js": "^0.7.36",
1921
"@types/node": "17.0.14",
2022
"@types/react": "17.0.38",
2123
"autoprefixer": "^10.4.2",
@@ -25,4 +27,4 @@
2527
"tailwindcss": "^3.0.18",
2628
"typescript": "4.5.5"
2729
}
28-
}
30+
}

edge-functions/user-agent-based-rendering/pages/_middleware.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { NextRequest, NextResponse } from 'next/server'
2+
import parser from 'ua-parser-js'
23

34
// RegExp for public files
45
const PUBLIC_FILE = /\.(.*)$/
@@ -16,10 +17,11 @@ export function middleware(req: NextRequest) {
1617
return NextResponse.rewrite(url)
1718
}
1819

20+
// Parse user agent
21+
const ua = parser(req.headers.get('user-agent')!)
22+
1923
// Check the viewport
20-
const viewport = ['android', 'ios'].includes(req.ua?.os.name?.toLowerCase()!)
21-
? 'mobile'
22-
: 'desktop'
24+
const viewport = ua.device.type === 'mobile' ? 'mobile' : 'desktop'
2325

2426
// Update the expected url
2527
url.pathname = `_viewport/${viewport}${url.pathname}`

0 commit comments

Comments
 (0)