mirror of
https://github.com/ajnart/homarr.git
synced 2026-05-06 17:55:41 +02:00
✨ Add device-id cookie for future selection of default layout per device
This commit is contained in:
@@ -2,3 +2,4 @@ export const REPO_URL = 'ajnart/homarr';
|
||||
export const ICON_PICKER_SLICE_LIMIT = 36;
|
||||
export const COOKIE_LOCALE_KEY = 'config-locale';
|
||||
export const COOKIE_COLOR_SCHEME_KEY = 'color-scheme';
|
||||
export const COOKIE_DEVICE_ID_KEY = 'deviceId';
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { env } from 'process';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { COOKIE_DEVICE_ID_KEY } from '../data/constants';
|
||||
import { getUrl } from './tools/server/url';
|
||||
import { client } from './utils/api';
|
||||
import { isMobileUserAgent } from './validations/mobile';
|
||||
|
||||
const skippedUrls = [
|
||||
'/onboard',
|
||||
@@ -19,20 +20,21 @@ let cachedUserCount = 0;
|
||||
|
||||
export async function middleware(req: NextRequest) {
|
||||
const url = req.nextUrl.clone();
|
||||
const deviceId = req.cookies.get(COOKIE_DEVICE_ID_KEY)?.value ?? null;
|
||||
|
||||
// Do not redirect if the url is in the skippedUrls array
|
||||
if (skippedUrls.some((skippedUrl) => url.pathname.startsWith(skippedUrl))) {
|
||||
return NextResponse.next();
|
||||
return HomarrResponse.next(deviceId);
|
||||
}
|
||||
|
||||
// Do not redirect if we are on Vercel
|
||||
if (env.VERCEL) {
|
||||
return NextResponse.next();
|
||||
return HomarrResponse.next(deviceId);
|
||||
}
|
||||
|
||||
// Do not redirect if there are users in the database
|
||||
if (cachedUserCount > 0) {
|
||||
return NextResponse.next();
|
||||
return HomarrResponse.next(deviceId);
|
||||
}
|
||||
|
||||
// is only called from when there were no users in the database in this session (Since the app started)
|
||||
@@ -40,8 +42,24 @@ export async function middleware(req: NextRequest) {
|
||||
|
||||
// Do not redirect if there are users in the database
|
||||
if (cachedUserCount > 0) {
|
||||
return NextResponse.next();
|
||||
return HomarrResponse.next(deviceId);
|
||||
}
|
||||
|
||||
return NextResponse.redirect(getUrl(req) + '/onboard');
|
||||
}
|
||||
|
||||
const addDeviceIdToResponse = (response: NextResponse) => {
|
||||
response.cookies.set(COOKIE_DEVICE_ID_KEY, v4(), {
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 10), // 10 years
|
||||
});
|
||||
};
|
||||
|
||||
const HomarrResponse = {
|
||||
next: (deviceId: string | null) => {
|
||||
const response = NextResponse.next();
|
||||
if (!deviceId) {
|
||||
addDeviceIdToResponse(response);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user