# Deep Linking Code Snippets > Copy-paste code snippets for deep linking in Flutter and React Native: email verification, referrals, push notifications, and attribution tracking. - Canonical: https://redirectly.app/snippets - Site: [Redirectly](https://redirectly.app) — deferred deep linking for Flutter & React Native Copy-paste ready code for Flutter and React Native. Implement email verification, referrals, push notifications, and attribution tracking in minutes. ## Flutter ### Authentication #### Email Verification Deep Link Handler Handle email verification links with token parsing ```dart import 'package:redirectly_sdk/redirectly_sdk.dart'; import 'package:uni_links/uni_links.dart'; class EmailVerificationHandler { Future handleEmailVerification() async { try { // Listen to deep links deepLinkStream.listen((String? link) async { if (link != null && link.contains('/verify')) { final uri = Uri.parse(link); final token = uri.queryParameters['token']; if (token != null) { // Send verification request final response = await verifyEmail(token); if (response.success) { // Navigate to success screen navigateTo('/email-verified'); } } } }); } catch (e) { print('Email verification error: $e'); } } Future verifyEmail(String token) async { // Your verification logic return VerificationResponse(success: true); } } class VerificationResponse { final bool success; VerificationResponse({required this.success}); } ``` ### Marketing #### Referral Link Generator & Handler Create and handle referral links with reward tracking ```dart import 'package:redirectly_sdk/redirectly_sdk.dart'; import 'package:share_plus/share_plus.dart'; class ReferralManager { final redirectly = RedirectlySDK(); // Generate referral link Future generateReferralLink(String userId) async { final link = await redirectly.createDeepLink( route: '/referral', data: { 'referrer_id': userId, 'timestamp': DateTime.now().toIso8601String(), }, ); return link; } // Share referral link Future shareReferralLink(String userId) async { final link = await generateReferralLink(userId); await Share.share( 'Join me on the app! $link', subject: 'Join my referral program', ); } // Handle incoming referral Future handleReferral(String? referrerId) async { if (referrerId != null) { // Save referrer info await saveReferrerInfo(referrerId); // Track referral event await redirectly.trackEvent( name: 'referral_accepted', data: {'referrer_id': referrerId}, ); // Award bonus await awardReferralBonus(); } } Future saveReferrerInfo(String referrerId) async { // Save to local storage or API } Future awardReferralBonus() async { // Award points, credits, etc. } } ``` ### Analytics #### Campaign Attribution Reader Read and track attribution data from deep links ```dart import 'package:redirectly_sdk/redirectly_sdk.dart'; class AttributionReader { final redirectly = RedirectlySDK(); Future getAttributionData() async { try { // Get installation attribution final attribution = await redirectly.getAttribution(); return AttributionData( source: attribution['utm_source'] ?? 'organic', medium: attribution['utm_medium'] ?? 'direct', campaign: attribution['utm_campaign'] ?? 'none', content: attribution['utm_content'], term: attribution['utm_term'], clickId: attribution['click_id'], customData: attribution['custom_data'] ?? {}, ); } catch (e) { print('Attribution error: $e'); rethrow; } } Future trackAttributionEvent( String eventName, AttributionData attribution, ) async { await redirectly.trackEvent( name: eventName, data: { 'utm_source': attribution.source, 'utm_medium': attribution.medium, 'utm_campaign': attribution.campaign, 'utm_content': attribution.content, 'utm_term': attribution.term, }, ); } Future analyzeUserJourney(AttributionData attribution) async { print('User came from: ${attribution.source}'); print('Campaign: ${attribution.campaign}'); // Store for analytics await _storeAttributionLocally(attribution); } Future _storeAttributionLocally(AttributionData attribution) async { // Save to local database or preferences } } class AttributionData { final String source; final String medium; final String campaign; final String? content; final String? term; final String? clickId; final Map customData; AttributionData({ required this.source, required this.medium, required this.campaign, this.content, this.term, this.clickId, required this.customData, }); } ``` ### Engagement #### Push Notification Deep Link Handler Handle deep links from push notifications ```dart import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:redirectly_sdk/redirectly_sdk.dart'; class PushNotificationHandler { final messaging = FirebaseMessaging.instance; final redirectly = RedirectlySDK(); Future initializePushNotifications() async { // Request permissions await messaging.requestPermission(); // Handle notification when app is terminated final initialMessage = await messaging.getInitialMessage(); if (initialMessage != null) { _handleNotification(initialMessage); } // Handle notification when app is in foreground FirebaseMessaging.onMessage.listen((RemoteMessage message) { _handleNotification(message); }); // Handle notification tap when app is in background FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { _handleNotification(message); }); } void _handleNotification(RemoteMessage message) { final deepLink = message.data['deep_link']; final screenName = message.data['screen']; if (deepLink != null) { // Navigate via deep link navigateTo(deepLink); } else if (screenName != null) { // Navigate to specific screen navigateToScreen(screenName, message.data); } } void navigateTo(String deepLink) { // Your navigation logic print('Navigating to: $deepLink'); } void navigateToScreen(String screen, Map data) { // Navigate with parameters print('Navigating to screen: $screen'); } } ``` ### Configuration #### go_router Deep Link Configuration Set up go_router with Redirectly deep links ```dart import 'package:go_router/go_router.dart'; import 'package:redirectly_sdk/redirectly_sdk.dart'; final redirectly = RedirectlySDK(); final appRouter = GoRouter( // Handle initial deep link initialLocation: '/', // Route redirect logic redirect: (context, state) async { // Handle Redirectly deep links final deepLink = state.uri.toString(); if (deepLink.contains('redirectly.app')) { // Let Redirectly SDK handle the routing return await redirectly.handleDeepLink(deepLink); } return null; }, routes: [ GoRoute( path: '/', builder: (context, state) => const HomeScreen(), ), GoRoute( path: '/product/:id', builder: (context, state) { final productId = state.pathParameters['id']; return ProductDetailScreen(productId: productId ?? ''); }, ), GoRoute( path: '/referral', builder: (context, state) { final referrerId = state.uri.queryParameters['referrer_id']; return ReferralScreen(referrerId: referrerId); }, ), GoRoute( path: '/verify', builder: (context, state) { final token = state.uri.queryParameters['token']; return EmailVerificationScreen(token: token ?? ''); }, ), GoRoute( path: '/promo/:code', builder: (context, state) { final promoCode = state.pathParameters['code']; return PromoScreen(code: promoCode ?? ''); }, ), ], ); // Handle incoming links Future setupDeepLinkHandling() async { redirectly.onDeepLinkReceived = (deepLink, data) { // Custom handling for specific routes if (deepLink.contains('/product/')) { // Analytics tracking redirectly.trackEvent( name: 'product_opened', data: data, ); } }; } ``` #### Basic SDK Initialization Initialize Redirectly SDK in your Flutter app ```dart import 'package:flutter/material.dart'; import 'package:redirectly_sdk/redirectly_sdk.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize Redirectly SDK await RedirectlySDK.initialize( apiKey: 'your_api_key_here', subdomain: 'your_subdomain', // Optional: Enable debug logging enableDebugLogging: true, ); runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State createState() => _MyAppState(); } class _MyAppState extends State { late RedirectlySDK _redirectly; @override void initState() { super.initState(); _initializeRedirectly(); } Future _initializeRedirectly() async { _redirectly = RedirectlySDK.instance; // Listen for deep links _redirectly.deepLinkStream.listen((deepLink) { _handleDeepLink(deepLink); }); // Get initial deep link (if app was opened via link) final initialLink = await _redirectly.getInitialDeepLink(); if (initialLink != null) { _handleDeepLink(initialLink); } } void _handleDeepLink(String deepLink) { // Route based on deep link final uri = Uri.parse(deepLink); print('Deep link received: ${uri.path}'); // Navigate to appropriate screen } @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: const HomeScreen(), ); } @override void dispose() { _redirectly.dispose(); super.dispose(); } } ``` ## React Native ### Authentication #### Email Verification Deep Link Handler Handle email verification links with token extraction ```typescript import { useEffect } from 'react'; import { Alert } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import dynamicLinks from '@react-native-firebase/dynamic-links'; interface VerificationParams { token: string; } export const useEmailVerificationHandler = () => { const navigation = useNavigation(); useEffect(() => { const unsubscribe = dynamicLinks().onLink(async (link) => { const url = new URL(link.url); if (url.pathname === '/verify') { const token = url.searchParams.get('token'); if (token) { try { const response = await verifyEmail(token); if (response.success) { Alert.alert('Success', 'Email verified successfully'); navigation.navigate('EmailVerified'); } else { Alert.alert('Error', 'Failed to verify email'); } } catch (error) { console.error('Verification error:', error); Alert.alert('Error', 'An error occurred during verification'); } } } }); // Handle initial link dynamicLinks() .getInitialLink() .then((link) => { if (link?.url) { const url = new URL(link.url); if (url.pathname === '/verify') { const token = url.searchParams.get('token'); if (token) handleVerification(token); } } }); return unsubscribe; }, [navigation]); }; async function verifyEmail(token: string) { const response = await fetch('/api/verify-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); return response.json(); } async function handleVerification(token: string) { // Handle verification logic } ``` ### Marketing #### Referral Link Handler Manage referral links and attribution ```typescript import { useEffect } from 'react'; import { Share, Alert } from 'react-native'; import dynamicLinks from '@react-native-firebase/dynamic-links'; interface ReferralData { referrerId: string; timestamp: string; rewardAmount?: number; } export const useReferralHandler = (userId: string) => { // Generate referral link const generateReferralLink = async (): Promise => { const link = await dynamicLinks().buildShortLink( { link: `https://redirectly.app/referral?referrer_id=${userId}`, domainUriPrefix: 'https://yourapp.page.link', ios: { bundleId: 'com.example.app' }, android: { packageName: 'com.example.app' }, }, dynamicLinks.ShortLinkType.SHORT, ); return link; }; // Share referral link const shareReferralLink = async () => { try { const link = await generateReferralLink(); await Share.share({ message: `Join me on the app! ${link}`, title: 'Referral Program', url: link, // iOS }); } catch (error) { console.error('Share error:', error); } }; // Handle incoming referral const handleIncomingReferral = async ( referralData: ReferralData, ) => { try { // Save referrer information await saveReferrerInfo(referralData.referrerId); // Track event await trackReferralEvent('referral_accepted', { referrer_id: referralData.referrerId, }); // Award bonus await awardReferralBonus(referralData.rewardAmount || 100); Alert.alert( 'Success', `You earned ${referralData.rewardAmount || 100} points!`, ); } catch (error) { console.error('Referral handling error:', error); } }; // Listen for referral links useEffect(() => { const unsubscribe = dynamicLinks().onLink(async (link) => { const url = new URL(link.url); if (url.pathname === '/referral') { const referrerId = url.searchParams.get('referrer_id'); if (referrerId) { await handleIncomingReferral({ referrerId, timestamp: new Date().toISOString(), }); } } }); return unsubscribe; }, []); return { generateReferralLink, shareReferralLink }; }; async function saveReferrerInfo(referrerId: string) { // Save to AsyncStorage or API } async function trackReferralEvent( eventName: string, data: Record, ) { // Track with analytics } async function awardReferralBonus(amount: number) { // Award points/credits } ``` ### Analytics #### Attribution Data Reader Extract and track attribution data from deep links ```typescript import { useEffect, useState } from 'react'; import dynamicLinks from '@react-native-firebase/dynamic-links'; export interface AttributionData { source: string; medium: string; campaign: string; content?: string; term?: string; clickId?: string; customData: Record; } export const useAttributionReader = () => { const [attribution, setAttribution] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const readAttribution = async () => { try { // Get dynamic link data const link = await dynamicLinks().getInitialLink(); if (link) { const url = new URL(link.url); const params = url.searchParams; const attributionData: AttributionData = { source: params.get('utm_source') || 'organic', medium: params.get('utm_medium') || 'direct', campaign: params.get('utm_campaign') || 'none', content: params.get('utm_content') || undefined, term: params.get('utm_term') || undefined, clickId: params.get('click_id') || undefined, customData: { deviceId: link.utmParameters?.deviceId, timestamp: new Date().toISOString(), }, }; setAttribution(attributionData); // Track the attribution event await trackAttributionEvent('app_opened', attributionData); } } catch (error) { console.error('Attribution reading error:', error); } finally { setLoading(false); } }; readAttribution(); // Also listen for links received while app is open const unsubscribe = dynamicLinks().onLink((link) => { const url = new URL(link.url); const params = url.searchParams; const newAttribution: AttributionData = { source: params.get('utm_source') || 'organic', medium: params.get('utm_medium') || 'direct', campaign: params.get('utm_campaign') || 'none', content: params.get('utm_content') || undefined, term: params.get('utm_term') || undefined, clickId: params.get('click_id') || undefined, customData: {}, }; setAttribution(newAttribution); }); return unsubscribe; }, []); return { attribution, loading }; }; async function trackAttributionEvent( eventName: string, attribution: AttributionData, ) { // Send to your analytics provider console.log('Tracking event:', { event: eventName, utm_source: attribution.source, utm_medium: attribution.medium, utm_campaign: attribution.campaign, }); } ``` ### Engagement #### Push Notification Deep Link Handler Handle deep links from push notifications ```typescript import { useEffect } from 'react'; import { Alert } from 'react-native'; import messaging from '@react-native-firebase/messaging'; import { useNavigation } from '@react-navigation/native'; interface NotificationPayload { deepLink?: string; screen?: string; [key: string]: unknown; } export const usePushNotificationHandler = () => { const navigation = useNavigation(); useEffect(() => { // Request permission for notifications messaging().requestPermission(); // Handle notification when app is in foreground const unsubscribeForeground = messaging().onMessage( async (remoteMessage) => { const deepLink = (remoteMessage.data as NotificationPayload) ?.deepLink; const screen = (remoteMessage.data as NotificationPayload)?.screen; if (deepLink) { handleDeepLink(deepLink, navigation); } else if (screen) { navigateToScreen(screen, remoteMessage.data, navigation); } Alert.alert( remoteMessage.notification?.title || 'Notification', remoteMessage.notification?.body, ); }, ); // Handle notification when app is opened from background const unsubscribeBackground = messaging().onNotificationOpenedApp((remoteMessage) => { const deepLink = (remoteMessage.data as NotificationPayload) ?.deepLink; const screen = (remoteMessage.data as NotificationPayload)?.screen; if (deepLink) { handleDeepLink(deepLink, navigation); } else if (screen) { navigateToScreen(screen, remoteMessage.data, navigation); } }); // Check if app was opened from a notification messaging() .getInitialNotification() .then((remoteMessage) => { if (remoteMessage) { const deepLink = (remoteMessage.data as NotificationPayload) ?.deepLink; const screen = (remoteMessage.data as NotificationPayload)?.screen; if (deepLink) { handleDeepLink(deepLink, navigation); } else if (screen) { navigateToScreen(screen, remoteMessage.data, navigation); } } }); return () => { unsubscribeForeground(); unsubscribeBackground(); }; }, [navigation]); }; function handleDeepLink( deepLink: string, navigation: ReturnType, ) { const url = new URL(deepLink); const route = url.pathname; const params = Object.fromEntries(url.searchParams); navigation.navigate(route, params); } function navigateToScreen( screen: string, data: Record, navigation: ReturnType, ) { navigation.navigate(screen, data); } ``` ### Configuration #### React Navigation Deep Link Config Configure React Navigation for Redirectly deep links ```typescript import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import dynamicLinks from '@react-native-firebase/dynamic-links'; import { useEffect } from 'react'; const Stack = createNativeStackNavigator(); const linking = { prefixes: ['https://yourapp.page.link', 'yourapp://'], config: { screens: { Home: '/', ProductDetail: '/product/:id', Referral: { path: '/referral', parse: { referrer_id: String }, }, EmailVerification: { path: '/verify', parse: { token: String }, }, PromoScreen: { path: '/promo/:code', parse: { code: String }, }, }, }, }; export function RootNavigator() { const navigationRef = React.useRef(null); useEffect(() => { const unsubscribe = dynamicLinks().onLink((link) => { // Handle deep link const url = link.url; console.log('Deep link received:', url); }); // Check if app was opened from a deep link dynamicLinks() .getInitialLink() .then((link) => { if (link?.url) { console.log('Initial deep link:', link.url); } }); return unsubscribe; }, []); return ( } ref={navigationRef} > ({ title: `Product ${route.params.id}`, })} /> ); } ``` #### Basic SDK Initialization Initialize Redirectly SDK in your React Native app ```typescript import React, { useEffect } from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import dynamicLinks from '@react-native-firebase/dynamic-links'; interface RedirectlyConfig { apiKey: string; subdomain: string; enableDebugLogging?: boolean; } class RedirectlySDK { private static instance: RedirectlySDK; private config: RedirectlyConfig; private constructor(config: RedirectlyConfig) { this.config = config; this.initialize(); } static getInstance(config: RedirectlyConfig): RedirectlySDK { if (!RedirectlySDK.instance) { RedirectlySDK.instance = new RedirectlySDK(config); } return RedirectlySDK.instance; } private initialize() { if (this.config.enableDebugLogging) { console.log('Redirectly SDK initialized'); console.log('API Key:', this.config.apiKey.substring(0, 10) + '...'); console.log('Subdomain:', this.config.subdomain); } } async handleDeepLink(url: string): Promise { try { const deepLink = new URL(url); if (this.config.enableDebugLogging) { console.log('Processing deep link:', deepLink.pathname); } return true; } catch (error) { console.error('Deep link handling error:', error); return false; } } async trackEvent( eventName: string, data?: Record, ): Promise { if (this.config.enableDebugLogging) { console.log('Tracking event:', eventName, data); } // Send to analytics } } // Initialize in your app const Stack = createNativeStackNavigator(); const redirectly = RedirectlySDK.getInstance({ apiKey: 'your_api_key_here', subdomain: 'your_subdomain', enableDebugLogging: true, }); export function App() { useEffect(() => { // Handle initial deep link dynamicLinks() .getInitialLink() .then(async (link) => { if (link?.url) { await redirectly.handleDeepLink(link.url); } }); // Listen for deep links while app is open const unsubscribe = dynamicLinks().onLink(async (link) => { await redirectly.handleDeepLink(link.url); }); return unsubscribe; }, []); return ( ); } // Dummy screens function HomeScreen() { return null; } function DetailsScreen() { return null; } ``` ## Code Snippets for Every Use Case Our comprehensive library of code snippets covers the most common deep linking scenarios. Whether you're implementing email verification, tracking referrals, handling push notifications, or reading attribution data, we have production-ready code that you can copy and paste into your project. Each snippet is fully commented and includes error handling. We provide examples for both Flutter (Dart) and React Native (TypeScript) so you can choose the framework that works best for your team. The snippets demonstrate best practices and integration with popular libraries like go_router, React Navigation, Firebase, and OneSignal. All code is maintained and updated to work with the latest SDK versions. You can customize the snippets to match your specific needs, such as changing API endpoints, modifying navigation flows, or integrating with your own analytics platform. We recommend reviewing the code and testing thoroughly in your development environment before deploying to production. ## Related - [Flutter Guide](https://redirectly.app/flutter-deferred-deep-linking.md) — Complete guide to implementing deep linking in Flutter apps with Redirectly - [React Native Guide](https://redirectly.app/react-native-deferred-deep-linking.md) — Step-by-step instructions for React Native deep linking with Redirectly - [Deep Linking 101](https://redirectly.app/deep-linking-guide.md) — Learn the fundamentals of deep linking and best practices ## Need Custom Implementation? While our snippets cover common scenarios, every app is unique. Our team can help you customize the implementation for your specific use case, integrate with your backend, or set up advanced attribution tracking. - [Contact Us](https://redirectly.app/contact) - [View Integrations](https://redirectly.app/integrations.md) --- Full site index for AI agents: https://redirectly.app/llms.txt