search
HomeWeb Front-endJS TutorialMastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration

Scenario

Imagine you have an eCommerce app named ShopEasy, and you want users who click on product links in emails, messages, or social media to be redirected directly to the relevant product page in the app, instead of the website.


Step 1: Opengraph Configuration in nodejs server for link preview:

Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration

Open Graph is a protocol used by web developers to control how URLs are represented when shared on social media platforms like Facebook, Twitter, LinkedIn, and others. By using Open Graph tags in the HTML of a webpage, you can dictate what content will be shown in the preview when a user shares the link.

To use these OpenGraph tags in a React Native app, you would handle the links to your server (such as https://ShopEasy.com/${type}/${id}) using deep linking or universal links. When users share these links, platforms like Facebook, Twitter, or iMessage will automatically display the content preview based on the OpenGraph tags you've defined.

/routes/share.js

const express = require('express');
const app = express();
const path = require('path');

// Serve static files (e.g., images, CSS, JavaScript)
app.use(express.static(path.join(__dirname, 'public')));

// Route to serve the OpenGraph meta tags
app.get('/:type/:id', (req, res) => { // type: product/category
    const productId = req.params.id;

    // Fetch product details from a database or API (placeholder data for this example)
    const product = {
        id: productId,
        name: 'Sample Product',
        description: "'This is a sample product description.',"
        imageUrl: 'https://ShopEasy.com/images/sample-product.jpg',
        price: '$19.99',
    };

    // Serve HTML with OpenGraph meta tags
    res.send(`
        
        
        
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration</title>

            <!-- OpenGraph Meta Tags -->
            <meta property="og:title" content="Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration">
            <meta property="og:description" content="${product.description}">
            <meta property="og:image" content="${product.imageUrl}">
            <meta property="og:url" content="https://example.com/product/${product.id}">
            <meta property="og:type" content="product">
            <meta property="og:price:amount" content="${product.price}">
            <meta property="og:price:currency" content="USD">

            <!-- Twitter Card Meta Tags (optional) -->
            <meta name="twitter:card" content="summary_large_image">
            <meta name="twitter:title" content="Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration">
            <meta name="twitter:description" content="${product.description}">
            <meta name="twitter:image" content="${product.imageUrl}">

        
        
            <h1 id="Mastering-Deep-Linking-and-Universal-Links-in-React-Native-OpenGraph-Share-amp-Node-js-Integration">Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration</h1>
            <p>${product.description}</p>
            <img src="/static/imghwm/default1.png" data-src="${product.imageUrl}" class="lazy" alt="Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration">
            <p>Price: ${product.price}</p>
        
        
    `);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});


Step 2: iOS Setup and Configuration:

a) (For production) Prepare the apple-app-site-association File

The apple-app-site-association (AASA) file is a JSON file that tells iOS which URLs should open your app. Here's how you might set it up for your eCommerce app:

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appIDs": ["ABCDE12345.com.shopeasy.app"],
                "paths": [
                    "/product/*",
                    "/category/*",
                    "/cart",
                    "/checkout"
                ]
            }
        ]
    }
}
  • appIDs: . Your app’s identifier, combining your Apple Team ID (ABCDE12345) with your app’s bundle identifier (com.shopeasy.app).
  • paths: The paths on your website that should open in your app.
  • /product/*: Any product page (like https://www.shopeasy.com/product/123) should open in the app.
  • /category/*: Any category page (like https://www.shopeasy.com/category/shoes).
  • /cart and /checkout: The user's cart and checkout pages should also open in the app.

b) (For production) Host the apple-app-site-association File

After you construct the association file, place it in your site’s .well-known directory. The file’s URL should match the following format:

https:///.well-known/apple-app-site-association(eg: https://www.shopeasy.com/.well-known/apple-app-site-association)
You must host the file using https:// with a valid certificate and with no redirects.

c) Enable Associated Domains in Xcode

i) Open Xcode:
Open your ShopEasy project in Xcode.

ii) Add Associated Domains Capability:
Go to the "Signing & Capabilities" tab.
Click the "+" button and add "Associated Domains."

iii) Add Your Domain:
Under the Associated Domains section, add your domain prefixed with applinks:.
For example:
:
i) Service applinks: Used for deep linking and app-to-web interaction, allowing your app to handle specific URLs directly.
ii) Service webcredentials: Used to enable AutoFill for credentials, allowing users to seamlessly use saved passwords across your app and website.
Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration

For dev:

applinks:shopeasy
webcredentials:shopeasy

For production:

applinks:shopeasy.com
webcredentials:shopeasy.com

d)(ref) In Info.plist configuring URL Schemes: (URL schemes are useful when you want to open your app via a link that’s not necessarily a web URL, allowing deep linking within your app or launching it from another app.)

where:
CFBundleURLName: A human-readable name for the URL scheme. This can be any descriptive string.
CFBundleURLSchemes: The actual URL scheme your app supports. It should be a unique string like shopeasy/showeasy.com(if production set).

    <array>
...
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>shopeasy</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>shopeasy</string>
            </array>
        </dict>
    </array>

d) In AppDelegate.mm:

#import <react>

// ...
// Add Below Code for DeepLinks

- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<uiapplicationopenurloptionskey> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}


- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray<id>> * _Nullable))restorationHandler
{
return [RCTLinkingManager application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [RCTLinkingManager application:application openURL:url
sourceApplication:sourceApplication annotation:annotation];
}

//DEEP LINKS TILL HERE

@end
</id></uiapplicationopenurloptionskey></react>

e) Testing deeplink device:

This should open the app.

npx uri-scheme open "shopeasy://product/mobile" --ios

or

xcrun simctl openurl booted "shopeasy://product/mobile"

Step 3: Android Setup and Configuration:

i) In AndroidManifest.xml:

    <application... ... android:launchmode="singleTask">

    <!-- DEEP LINKS HERE -->

   <intent-filter>
        <action android:name="android.intent.action.VIEW"></action>
        <category android:name="android.intent.category.DEFAULT"></category>
        <category android:name="android.intent.category.BROWSABLE"></category>
        <data android:scheme="shopeasy"></data>
    </intent-filter>

        <intent-filter>
        <action android:name="android.intent.action.VIEW"></action>
          <category android:name="android.intent.category.DEFAULT"></category>
          <category android:name="android.intent.category.BROWSABLE"></category>
          <data android:scheme="http"></data>
          <data android:scheme="https"></data>
          <data android:host="localhost"></data>
          <!-- REPLACE the HOST with app domain like shopeasy.com -->
        </intent-filter>
   <!-- DEEP LINKS HERE -->

/>
</application...>

ii) Check in android:
adb shell am start -W -a android.intent.action.VIEW -d "shopeasy://product/apple" com.shopeasy
or
Click on this link in emulator if route is working:
http://localhost:3000/share/product/iphone


Step 3: Usage in React Native App:

Navigation.jsx

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import MainNavigator from './MainNavigator';
import { navigationRef } from '../utils/NavigationUtil';

const config = {
  screens: {
    ProductScreen: '/product/:id',
    CategoryScreen: '/category/:name',
  },
};

const linking = {
  prefixes: ['shopeasy://', 'https://shopeasy.com', 'http://localhost:3000'], 
  config,
};

const Navigation: React.FC = () => {
  return (
    <navigationcontainer linking="{linking}" ref="{navigationRef}">
      <mainnavigator></mainnavigator>
    </navigationcontainer>
  );
};

export default Navigation;

App.jsx

  useEffect(() => {
    // Retrieve the initial URL that opened the app (if any) and handle it as a deep link.
    Linking.getInitialURL().then(url => {
      handleDeepLink({ url }, 'CLOSE'); // Pass the URL and an action ('CLOSE') to handleDeepLink function.
    });

    // Add an event listener to handle URLs opened while the app is already running.
    Linking.addEventListener('url', event => handleDeepLink(event, 'RESUME'));
    // When the app is resumed with a URL, handle it as a deep link with the action ('RESUME').

    // Cleanup function to remove the event listener when the component unmounts.
    return () => {
      Linking.removeEventListener('url', event => handleDeepLink(event, 'RESUME'));
    };
  }, []);

CLOSE/RESUME is optional and is passed handle as per requirement.

The above is the detailed content of Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.