Skip to main content

Mobile Redirection

note

With the completion of URL unification, this guide is now considered outdated.

warning

This section is not applicable in SSG pages.

Mobile redirection is a feature to redirect our user to mobile site if the user-agent is detected to be coming from mobile devices. This is not enabled automatically but rather opt-in, in case there's a page that's viewable in both desktop and mobile.

Legacy pages with getInitialProps

To enable mobile redirection, you need to add mobileRedirection property to your page component.

There's 3 way you can customize mobile redirection behavior. The first and the simplest one is by passing true. This will redirect user from desktop site to mobile site using the same pathname.

Simple Redirection

import { TravelokaPageComponent } from '@traveloka/core';

const Page: TravelokaPageComponent = props => {
return <div />;
};

Page.mobileRedirection = true;

If the user visits https://www.traveloka.com/user/profile from a mobile device, this rule will redirect them to https://m.traveloka.com/user/profile

Custom path redirection

The second method is by passing a custom string path. This way, instead of using the current path, you can redirect to any path you want.

import { TravelokaPageComponent } from '@traveloka/core';

const Page: TravelokaPageComponent = props => {
return <div />;
};

Page.mobileRedirection = '/random/path';

Advanced Redirection

The last one is the most complex one, reserved for advanced usage. You can pass function to mobileRedirection property that returns redirection object containing path that you want your user to be redirected to and optional status code.

This function will be called with express Request object and 2nd argument currentRoute containing route information

import { TravelokaPageComponent } from '@traveloka/core';

const Page: TravelokaPageComponent = props => {
return <div />;
};

Page.mobileRedirection = (req, currentRoute) => {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data
if (req.headers['Save-Data'] === 'on') {
return {
status: 302,
path: `/lite/${currentRoute.pathname}`,
};
}

return {
path: currentRoute.pathname,
};
};

If you use this, it's recommended to annotate your page component with TravelokaPageComponent to get proper type information.