본문으로 건너뛰기
엔지니어링 · · 5분 소요

크로스 플랫폼 링크 처리 패턴

작성자 Tolinku 팀
|
크로스플랫폼 링크 처리 패턴

딥 링크를 처리하려면 플랫폼별 진입점이 필요해요(iOS는 Universal Links, Android는 App Links, 웹은 URL 라우팅). 하지만 실제 라우팅 로직, 즉 "이 URL은 이 파라미터로 이 화면에 연결된다"를 결정하는 부분은 공유할 수 있어요. 이 글에서는 링크 처리 코드를 한 번만 작성하고 플랫폼별로 맞춰 쓰는 패턴을 다뤄요.

크로스 플랫폼 전체 개요는 다음 글을 참고하세요: 2026년 크로스 플랫폼 딥 링킹 가이드. 라우팅 기본 개념은 다음 글을 참고하세요: 딥 링크 라우팅: 사용자를 올바른 화면으로 보내는 방법.

문제

플랫폼마다 딥 링크를 받는 API가 달라요:

  • iOS: application(_:continue:restorationHandler:) AppDelegate 또는 SceneDelegate에서
  • Android: Intent에 ACTION_VIEW 를 담아 Activity로 전달
  • 웹: window.location 페이지 로드 시 파싱
  • Capacitor/Ionic: App.addListener('appUrlOpen', ...)
  • React Native: Linking.addEventListener('url', ...)
  • Flutter: uni_links 또는 app_links package

URL이 들어오는 API는 다르지만 질문은 항상 같아요. 이 경로와 쿼리 파라미터라면 사용자에게 어떤 화면을 보여줘야 할까요?

패턴 1: 공유 라우트 테이블

라우트를 플랫폼에 상관없는 형식으로 정의하세요. 각 플랫폼의 진입점은 URL을 파싱해서 공유 테이블로 넘겨요.

라우트 정의

// routes.ts (모든 플랫폼에서 공유)
interface RouteMatch {
  screen: string;
  params: Record<string, string>;
}

interface RoutePattern {
  pattern: RegExp;
  screen: string;
  paramNames: string[];
}

const routes: RoutePattern[] = [
  {
    pattern: /^\/products\/([^/]+)$/,
    screen: 'ProductDetail',
    paramNames: ['productId']
  },
  {
    pattern: /^\/offers\/([^/]+)$/,
    screen: 'OfferDetail',
    paramNames: ['offerId']
  },
  {
    pattern: /^\/referral\/([^/]+)$/,
    screen: 'Referral',
    paramNames: ['referrerId']
  },
  {
    pattern: /^\/categories\/([^/]+)\/products$/,
    screen: 'CategoryProducts',
    paramNames: ['categoryId']
  },
  {
    pattern: /^\/search$/,
    screen: 'Search',
    paramNames: []
  }
];

export function matchRoute(urlString: string): RouteMatch | null {
  const url = new URL(urlString);
  const path = url.pathname;

  for (const route of routes) {
    const match = path.match(route.pattern);
    if (match) {
      const params: Record<string, string> = {};
      route.paramNames.forEach((name, i) => {
        params[name] = match[i + 1];
      });

      // 쿼리 파라미터도 포함
      url.searchParams.forEach((value, key) => {
        params[key] = value;
      });

      return { screen: route.screen, params };
    }
  }

  return null;
}

플랫폼별 진입점

iOS (Swift):

func application(_ application: UIApplication,
                 continue userActivity: NSUserActivity,
                 restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    guard let url = userActivity.webPageUrl else { return false }

    // 공유 라우팅 로직 호출 (JavaScript 브리지를 쓰거나 Swift로 다시 구현)
    let route = DeepLinkRouter.match(url: url)
    if let route = route {
        navigate(to: route.screen, params: route.params)
        return true
    }
    return false
}

Android (Kotlin):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    intent?.data?.let { uri ->
        val route = DeepLinkRouter.match(uri.toString())
        route?.let { navigateTo(it.screen, it.params) }
    }
}

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    intent.data?.let { uri ->
        val route = DeepLinkRouter.match(uri.toString())
        route?.let { navigateTo(it.screen, it.params) }
    }
}

웹:

// 페이지 로드 또는 라우트 변경 시
const route = matchRoute(window.location.href);
if (route) {
  renderScreen(route.screen, route.params);
}

패턴 2: URL을 액션에 매핑

URL을 화면에 직접 매핑하지 말고 액션에 매핑하세요. 그러면 딥 링크 레이어와 내비게이션 레이어가 분리돼요.

// actions.ts
type DeepLinkAction =
  | { type: 'VIEW_PRODUCT'; productId: string; source?: string }
  | { type: 'VIEW_OFFER'; offerId: string }
  | { type: 'APPLY_REFERRAL'; referrerId: string }
  | { type: 'SEARCH'; query: string }
  | { type: 'OPEN_HOME' };

export function urlToAction(urlString: string): DeepLinkAction {
  const url = new URL(urlString);
  const path = url.pathname;
  const query = url.searchParams;

  const productMatch = path.match(/^\/products\/([^/]+)$/);
  if (productMatch) {
    return {
      type: 'VIEW_PRODUCT',
      productId: productMatch[1],
      source: query.get('ref') ?? undefined
    };
  }

  const offerMatch = path.match(/^\/offers\/([^/]+)$/);
  if (offerMatch) {
    return { type: 'VIEW_OFFER', offerId: offerMatch[1] };
  }

  const referralMatch = path.match(/^\/referral\/([^/]+)$/);
  if (referralMatch) {
    return { type: 'APPLY_REFERRAL', referrerId: referralMatch[1] };
  }

  if (path === '/search') {
    return { type: 'SEARCH', query: query.get('q') ?? '' };
  }

  return { type: 'OPEN_HOME' };
}

각 플랫폼은 자체 액션 핸들러를 구현해요:

// iOS, Android, 웹이 각각 이 인터페이스를 구현
interface ActionHandler {
  handleAction(action: DeepLinkAction): void;
}

// 예: React Native 핸들러
class RNActionHandler implements ActionHandler {
  handleAction(action: DeepLinkAction) {
    switch (action.type) {
      case 'VIEW_PRODUCT':
        navigation.navigate('ProductDetail', {
          productId: action.productId
        });
        break;
      case 'APPLY_REFERRAL':
        // 추천 정보를 저장한 뒤 이동
        ReferralStore.save(action.referrerId);
        navigation.navigate('Home');
        break;
      // ...
    }
  }
}

이 패턴은 이동하기 전에 추천 코드 저장이나 분석 이벤트 전송 같은 부수 작업이 필요한 액션이 있을 때 유용해요.

패턴 3: 설정 기반 라우트

딥 링크 경로가 많은 앱이라면 모든 플랫폼이 읽는 설정 파일에 라우트를 정의하세요:

{
  "routes": [
    {
      "path": "/products/:productId",
      "screen": "ProductDetail",
      "requiresAuth": false
    },
    {
      "path": "/account/settings",
      "screen": "AccountSettings",
      "requiresAuth": true
    },
    {
      "path": "/offers/:offerId",
      "screen": "OfferDetail",
      "requiresAuth": false
    },
    {
      "path": "/checkout/:cartId",
      "screen": "Checkout",
      "requiresAuth": true
    }
  ]
}

공유 파서가 경로 패턴을 정규식으로 바꿔요:

function pathToRegex(path: string): { regex: RegExp; paramNames: string[] } {
  const paramNames: string[] = [];
  const regexStr = path.replace(/:([^/]+)/g, (_, name) => {
    paramNames.push(name);
    return '([^/]+)';
  });
  return {
    regex: new RegExp(`^${regexStr}$`),
    paramNames
  };
}

이렇게 하면 플랫폼 간 라우트 정의가 항상 맞춰져요. 새 딥 링크 경로를 추가할 때는 설정 파일만 한 번 수정하면 돼요.

플랫폼별 차이 처리

라우팅 로직을 공유하더라도 플랫폼마다 다르게 동작하는 부분이 있어요.

인증 게이트

딥 링크가 인증이 필요한 화면을 가리키면, 동작은 플랫폼 관례에 따라 달라져요:

function handleAuthenticatedRoute(
  route: RouteMatch,
  isLoggedIn: boolean,
  platform: 'ios' | 'android' | 'web'
) {
  if (isLoggedIn) {
    navigate(route.screen, route.params);
    return;
  }

  // Save the intended destination
  saveDeepLinkDestination(route);

  // Platform-specific login flow
  if (platform === 'web') {
    // Redirect to login page with return URL
    window.location.href = `/login?returnTo=${encodeURIComponent(route.screen)}`;
  } else {
    // Show native login screen, then navigate after success
    showLoginScreen();
  }
}

폴백 동작

라우트가 매칭되지 않으면 플랫폼마다 폴백 방식이 달라요:

플랫폼 폴백
iOS 홈 화면 열기 또는 오류 표시
Android 홈 화면 열기 또는 시스템에 맡기기(브라우저)
웹 404 페이지 표시 또는 홈으로 리디렉션
function handleUnmatchedUrl(url: string, platform: string) {
  if (platform === 'web') {
    // 웹은 404 페이지를 보여줄 수 있음
    router.navigate('/not-found');
  } else {
    // 모바일 앱은 홈으로 자연스럽게 돌아가야 함
    router.navigate('/');
  }
}

라우트 동기화 유지

크로스 플랫폼 링크 처리에서 가장 어려운 부분은 다음 항목들 사이에서 라우트를 맞춰 두는 거예요:

  1. AASA 파일 (iOS 경로 패턴)
  2. assetlinks.json (Android 검증)
  3. AndroidManifest.xml (Intent 필터 경로 접두사)
  4. 앱 라우터 (클라이언트 측 라우트 정의)
  5. 백엔드 (웹용 서버 측 라우트 처리)

단일 정보 출처

라우트 정의 하나에서 플랫폼별 설정을 생성하세요:

// generate-configs.ts
import routeConfig from './routes.json';

// AASA components 생성
function generateAASA(routes: Route[]) {
  return {
    applinks: {
      details: [{
        appIDs: ['TEAMID.com.yourcompany.yourapp'],
        components: routes.map(r => ({
          '/': r.path.replace(/:([^/]+)/g, '*')
        }))
      }]
    }
  };
}

// Android Intent 필터 경로 생성
function generateIntentFilters(routes: Route[]) {
  // 중복 없는 경로 접두사 추출
  const prefixes = new Set(
    routes.map(r => '/' + r.path.split('/')[1])
  );
  return Array.from(prefixes);
}

이렇게 하면 누군가 AASA나 Intent 필터 업데이트를 깜빡해서 새 라우트가 한 플랫폼에서만 동작하는 흔한 버그를 막을 수 있어요.

크로스 플랫폼 라우트 테스트

플랫폼별 테스트 URL로 공용 라우팅 로직을 테스트하세요:

describe('matchRoute', () => {
  const testCases = [
    {
      url: 'https://yourdomain.com/products/abc123',
      expected: { screen: 'ProductDetail', params: { productId: 'abc123' } }
    },
    {
      url: 'https://yourdomain.com/products/abc123?ref=email&campaign=summer',
      expected: {
        screen: 'ProductDetail',
        params: { productId: 'abc123', ref: 'email', campaign: 'summer' }
      }
    },
    {
      url: 'https://yourdomain.com/unknown/path',
      expected: null
    }
  ];

  testCases.forEach(({ url, expected }) => {
    it(`${url} 매칭 확인`, () => {
      expect(matchRoute(url)).toEqual(expected);
    });
  });
});

크로스 플랫폼 앱을 위한 Tolinku

Tolinku 는 AASA와 assetlinks.json 호스팅을 맡아 주기 때문에 검증 파일이 자동으로 동기화돼요. 앱을 먼저 설치해야 하는 사용자를 위해 디퍼드 딥 링킹 앱을 먼저 설치해야 하는 사용자를 위한 것이에요.

하이브리드 앱에서 겪는 문제는 하이브리드 앱의 딥 링킹: 문제와 해결 방법을 참고하세요. 전체 가이드는 2026년 크로스 플랫폼 딥 링킹 가이드.

딥 링킹 팁을 메일로 받아 보세요

일주일에 한 번만 보내요. 스팸은 없어요.

앱에 딥 링킹을 추가해 볼까요?

유니버설 링크, 앱 링크, 디퍼드 딥 링킹, 분석을 몇 분 만에 설정할 수 있어요. 무료로 시작하세요.