Skip to content

Commit 1f9cda5

Browse files
committed
Add mobile detection to the root route to apply to all navigations
1 parent 181a38e commit 1f9cda5

3 files changed

Lines changed: 25 additions & 17 deletions

File tree

src/routes/__root.tsx

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
ClientOnly,
66
createRootRouteWithContext,
77
HeadContent,
8+
redirect,
89
ScriptOnce,
910
Scripts,
1011
} from "@tanstack/react-router";
@@ -16,6 +17,7 @@ import { Button } from "@/components/ui/button";
1617
import { Card, CardContent, CardHeader } from "@/components/ui/card";
1718
import { Toaster } from "@/components/ui/sonner";
1819
import { client, idbName } from "@/db";
20+
import { getIsMobile } from "@/server/functions/getIsMobile";
1921
import { seo } from "@/utils/seo";
2022
import appCss from "../styles.css?url";
2123

@@ -24,6 +26,20 @@ interface MyRouterContext {
2426
}
2527

2628
export const Route = createRootRouteWithContext<MyRouterContext>()({
29+
beforeLoad: async ({ location }) => {
30+
// Skip redirect if already on /mobile to avoid infinite loop
31+
if (location.pathname === "/mobile") {
32+
return;
33+
}
34+
35+
const isMobile = await getIsMobile();
36+
37+
if (isMobile) {
38+
throw redirect({
39+
to: "/mobile",
40+
});
41+
}
42+
},
2743
head: () => ({
2844
meta: [
2945
{

src/routes/index.tsx

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,7 @@
11
import { createFileRoute, redirect } from "@tanstack/react-router";
2-
import { createServerFn } from "@tanstack/react-start";
3-
import { getRequestHeader } from "@tanstack/react-start/server";
4-
5-
const getIsMobile = createServerFn().handler(async () => {
6-
const userAgent = getRequestHeader("user-agent") || "";
7-
const mobileRegex =
8-
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
9-
return mobileRegex.test(userAgent);
10-
});
112

123
export const Route = createFileRoute("/")({
134
beforeLoad: async () => {
14-
const isMobile = await getIsMobile();
15-
16-
if (isMobile) {
17-
throw redirect({
18-
to: "/mobile",
19-
});
20-
}
21-
225
throw redirect({
236
to: "/projects",
247
});
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { createServerFn } from "@tanstack/react-start";
2+
import { getRequestHeader } from "@tanstack/react-start/server";
3+
4+
export const getIsMobile = createServerFn().handler(async () => {
5+
const userAgent = getRequestHeader("user-agent") || "";
6+
const mobileRegex =
7+
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
8+
return mobileRegex.test(userAgent);
9+
});

0 commit comments

Comments
 (0)