Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

general: log server load events to tweak vercel bill #808

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ NEXT_PUBLIC_API_KEY_MAPTILER=7dlhLl3hiXQ1gsth0kGu

# https://graphhopper.com/dashboard/#/apikeys
NEXT_PUBLIC_API_KEY_GRAPHHOPPER=f189b841-6529-46c6-8a91-51f17477dcda

# https://us.umami.is/websites - this key is for development only, prod code in vercel
UMAMI_WEBSITE_ID=5e4d4917-9031-42f1-a26a-e71d7ab8e3fe
5 changes: 4 additions & 1 deletion pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import Document, {
} from 'next/document';
import type { DocumentContext } from 'next/dist/shared/lib/utils';
import {
DocumentHeadTags,
documentGetInitialProps,
DocumentHeadTags,
DocumentHeadTagsProps,
} from '@mui/material-nextjs/v13-pagesRouter';
import { getServerIntl } from '../src/services/intlServer';
Expand All @@ -20,6 +20,7 @@ import { PROJECT_ID, setProjectForSSR } from '../src/services/project';
import { FaviconsOpenClimbing } from '../src/helpers/FaviconsOpenClimbing';
import { LANGUAGES } from '../src/config.mjs';
import styled from '@emotion/styled';
import { logRequest } from '../src/server/logRequest';

const Body = styled.body`
@media (prefers-color-scheme: light) {
Expand Down Expand Up @@ -104,6 +105,8 @@ MyDocument.getInitialProps = async (

const initialProps = await documentGetInitialProps(ctx);

logRequest(ctx, serverIntl);

return {
...initialProps,
serverIntl,
Expand Down
16 changes: 10 additions & 6 deletions src/components/App/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import { NextPageContext } from 'next';

const DEFAULT_VIEW: View = ['4', '50', '14'];

const isLocalhostOrNgnix = (ip: string) => ['127.0.0.1', '::1'].includes(ip);

type IpApiResponse = {
status: string;
lat: number;
Expand All @@ -39,14 +37,20 @@ const getViewFromIp = async (ip: string): Promise<View> => {
}
};

export const getViewFromRequest = async (
req: NextPageContext['req'],
): Promise<View> => {
const isLocalhostOrNgnix = (ip: string) => ['127.0.0.1', '::1'].includes(ip);

export const getIp = (req: NextPageContext['req']) => {
const remoteIp = req.socket.remoteAddress;
const fwdIp = ((req.headers['x-forwarded-for'] as string) || '') // ngnix: proxy_set_header X-Forwarded-For $remote_addr;
.split(',')[0]
.trim();
const ip = isLocalhostOrNgnix(remoteIp) ? fwdIp : remoteIp;
return isLocalhostOrNgnix(remoteIp) ? fwdIp : remoteIp;
};

export const getViewFromRequest = async (
req: NextPageContext['req'],
): Promise<View> => {
const ip = getIp(req);
const view = ip ? await getViewFromIp(ip) : null;
return view ?? DEFAULT_VIEW;
};
Expand Down
47 changes: 47 additions & 0 deletions src/server/logRequest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { DocumentContext } from 'next/dist/shared/lib/utils';
import { Intl } from '../services/intl';
import { fetchJson } from '../services/fetch';
import { getIp } from '../components/App/helpers';

// On some days we have 100k of page loads of Vercel Serveless Function.
// Because of that, we had to switch to paid Pro plan from the Hobby.
//
// We need to debug where this traffic comes from to be able to optimize it.

// This function works server-side only to omit any tracking cookies.

export const logRequest = (ctx: DocumentContext, intl: Intl) => {
const { host, referrer } = ctx.req.headers;
const data = {
type: 'event',
payload: {
website: process.env.UMAMI_WEBSITE_ID,
url: ctx.asPath,
hostname: host,
language: intl.lang,
referrer,
screen: '1280x800',
},
};
const headers = {
'X-Client-IP': getIp(ctx.req),
'User-Agent': ctx.req.headers['user-agent'],
};

console.log('umami data', JSON.stringify({ data, headers }, null, 2));

// Promise omitted intentionally
fetchJson('https://cloud.umami.is/api/send', {
nocache: true,
method: 'POST',
headers,
body: JSON.stringify(data),
}).then(
(response) => {
console.log('umami response', response);
},
(error) => {
console.error('umami error', error);
},
);
};
2 changes: 1 addition & 1 deletion src/services/intl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { publishDbgObject } from '../utils';

type Values = { [variable: string]: string | number };

interface Intl {
export interface Intl {
lang: string;
messages: MessagesType | {};
}
Expand Down
3 changes: 2 additions & 1 deletion src/services/intlServer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import acceptLanguageParser from 'accept-language-parser';
import nextCookies from 'next-cookies';
import { LANGUAGES } from '../config.mjs';
import { Intl } from './intl';

// the files are not imported in main bundle
const getMessages = async (lang) =>
Expand Down Expand Up @@ -33,7 +34,7 @@ const resolveCurrentLang = (ctx) => {
return getLangFromAcceptHeader(ctx) ?? DEFAULT_LANG;
};

export const getServerIntl = async (ctx) => {
export const getServerIntl = async (ctx): Promise<Intl> => {
const lang = resolveCurrentLang(ctx);
const vocabulary = await getMessages('vocabulary');
const messages = lang === DEFAULT_LANG ? {} : await getMessages(lang);
Expand Down
Loading