Mobile development · Advanced · 26 min
Open Larkfield screens from links with deep links, universal links and app links
By Padding · Updated 18 Nov 2026
Expo SDK 58 · Expo Router 58 · Node.js 26
You will make a link in a text message open the right Larkfield appointment, with a custom scheme, iOS universal links and Android app links served from the clinic domain, a tested rewrite for old and short links, and links that wait for sign-in.
On this page
Larkfield Clinic sends each patient a text message the day before an appointment. Today that message says "open the app and find your booking". This part makes the message carry a link that opens the booking itself, whether the patient taps it in Messages, WhatsApp or an email.
There are three kinds of link, and the app needs all three:
- A custom scheme link,
larkfield://appointments/42. It is quick to set up and good for testing and for links between your own apps, but any app can claim the same scheme, so do not send it to patients. - An iOS universal link,
https://larkfield.example/appointments/42. iOS opens it in the app only after it has checked a file on the clinic's domain that names your app. - An Android app link, the same
https://address. Android checks a different file on the same domain.
Expo Router does the mapping from address to screen for you: the path after the domain is the route, so /appointments/42 opens src/app/appointments/[id].tsx with id set to 42. You do not write a linking table. What you do write is the app configuration, the two files on the domain, a small rewrite for links in older formats, and the rule that a link only ever names an appointment: the server decides whether this patient may see it.
larkfield.example stands in for the clinic's domain throughout. The .example ending is reserved for documentation, so nothing real lives there. Replace it with a domain you control when you build for a phone.
Step 1 · Keep the link settings in one file
Three things have to agree: the app configuration, the iOS file on the domain and the Android file on the domain. If the domain or the app ID is typed in three places, one of them will drift. Put the settings in one small JSON file at the project root, and read it from everywhere else.
Replace the example values with your own: the clinic's domain, the iOS bundle identifier and the Android package name you will ship under. The path prefixes are the parts of the site that should open the app; everything else on the domain stays in the browser.
cd ~/larkfield-app-demo
cat > app-links.json <<'JSON'
{
"host": "larkfield.example",
"pathPrefixes": ["/appointments/", "/r/"],
"iosBundleId": "com.example.larkfield",
"androidPackage": "com.example.larkfield"
}
JSON/appointments/ covers full links such as /appointments/42. /r/ is for short links such as /r/42, which you will rewrite later. Short links matter when the reminder goes out as a plain SMS: a shorter link leaves room for the time, the clinic's phone number and a second language in the same message.
Check it worked
node -e "const l = require('./app-links.json'); console.log(l.host, l.pathPrefixes.join(' '))"It prints larkfield.example /appointments/ /r/. A typo in the JSON makes Node stop with a SyntaxError naming the position.
Step 2 · Add the scheme and the domain to the app configuration
A dynamic app.config.ts receives everything from app.json as config and returns the final configuration. That keeps the plugins and settings earlier parts added to app.json, such as the notifications plugin from part 5, and lets this file add the link settings from app-links.json:
cat > app.config.ts <<'TS'
import type { ConfigContext, ExpoConfig } from 'expo/config'
import links from './app-links.json'
export default ({ config }: ConfigContext): ExpoConfig => ({
...config,
name: config.name ?? 'Larkfield',
slug: config.slug ?? 'larkfield-app-demo',
// larkfield://appointments/42 for testing and links between your own apps
scheme: 'larkfield',
ios: {
...config.ios,
bundleIdentifier: links.iosBundleId,
// No https:// here: Apple's format is applinks:<domain>
associatedDomains: [`applinks:${links.host}`],
},
android: {
...config.android,
package: links.androidPackage,
intentFilters: [
{
action: 'VIEW',
autoVerify: true,
data: links.pathPrefixes.map((pathPrefix) => ({
scheme: 'https',
host: links.host,
pathPrefix,
})),
category: ['BROWSABLE', 'DEFAULT'],
},
],
},
})
TSThe scheme here wins over the one the template put in app.json. autoVerify: true tells Android to check the domain at install time, and the BROWSABLE category lets a browser or messaging app hand the link over. The Android filter only claims the two prefixes, so a link to the clinic's opening hours page still opens in the browser.
Check it worked
Ask Expo for the final configuration and pick out the link settings:
npx expo config --type public | grep -E "scheme|bundleIdentifier|package|applinks|autoVerify"You see something like scheme: 'larkfield', both IDs from app-links.json, 'applinks:larkfield.example' and autoVerify: true. Now see what the native projects will receive. Introspection runs the config plugins in memory without writing ios or android folders:
npx expo config --type introspect | grep -E "com.apple.developer.associated-domains|android:autoVerify"The output includes the com.apple.developer.associated-domains entitlement and an intent filter with android:autoVerify set to true. If either line is missing, check for a typo in app.config.ts, because nothing else will tell you until a phone ignores the link.
Step 3 · Try the custom scheme on a phone or simulator
A changed scheme, associated domain or intent filter only reaches a phone in a new native build. Expo Go cannot use your own scheme. Make a development build on your computer (or with EAS, as in build and submit an app with EAS) and start the app:
cd ~/larkfield-app-demo
npx expo run:iosWith the app running in the iOS simulator, send it a link from a second terminal:
npx uri-scheme@2.3.2 open "larkfield://appointments/42" --iosOn Android, use npx expo run:android, then --android in place of --ios, or send the link with adb:
adb shell am start -a android.intent.action.VIEW -d "larkfield://appointments/42"The root layout from part 1 sets unstable_settings.anchor to (tabs). That is what gives a screen opened straight from a link a back button to the tabs; without it, the patient lands on the appointment with nowhere to go back to.
Check it worked
The appointment screen opens with the check-up booking for 42, and the back button takes you to the tabs. Try larkfield://appointments/999 too: the screen says there is no such appointment instead of crashing. If uri-scheme or the simulator reports that it cannot open the URL, the installed build predates the larkfield scheme in app.config.ts; run npx expo run:ios again to make a new build.
Step 4 · Write the two files that prove you own the domain
Before iOS or Android open an https link in your app, they fetch a file from that domain and look for your app in it:
- iOS reads
https://<domain>/.well-known/apple-app-site-association(no file extension). Each entry joins your Apple Team ID and bundle identifier, and lists the paths the app handles. - Android reads
https://<domain>/.well-known/assetlinks.json. It names the package and the SHA-256 fingerprint of the certificate that signs the app.
Neither value is secret: both files are public by design. They still differ between a debug build, an internal build and the store build, so a small script writes the files from environment variables plus app-links.json, and refuses values in the wrong format:
mkdir -p scripts
cat > scripts/write-well-known.mjs <<'JS'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
const links = JSON.parse(readFileSync('app-links.json', 'utf8'))
const teamId = (process.env.APPLE_TEAM_ID ?? '').trim()
const fingerprints = (process.env.ANDROID_SHA256 ?? '')
.split(',')
.map((f) => f.trim().toUpperCase())
.filter(Boolean)
if (!/^[A-Z0-9]{10}$/.test(teamId)) {
console.error('Set APPLE_TEAM_ID to your 10-character Apple Team ID.')
process.exit(1)
}
const sha256 = /^([0-9A-F]{2}:){31}[0-9A-F]{2}$/
if (fingerprints.length === 0 || !fingerprints.every((f) => sha256.test(f))) {
console.error('Set ANDROID_SHA256 to one or more SHA-256 fingerprints (AA:BB:...), comma separated.')
process.exit(1)
}
const aasa = {
applinks: {
details: [
{
appIDs: [`${teamId}.${links.iosBundleId}`],
components: links.pathPrefixes.map((prefix) => ({
'/': `${prefix}*`,
comment: `Paths starting ${prefix} open the app`,
})),
},
],
},
}
const assetlinks = [
{
relation: ['delegate_permission/common.handle_all_urls'],
target: {
namespace: 'android_app',
package_name: links.androidPackage,
sha256_cert_fingerprints: fingerprints,
},
},
]
mkdirSync('public/.well-known', { recursive: true })
writeFileSync('public/.well-known/apple-app-site-association', JSON.stringify(aasa, null, 2) + '\n')
writeFileSync('public/.well-known/assetlinks.json', JSON.stringify(assetlinks, null, 2) + '\n')
console.log('Wrote public/.well-known/apple-app-site-association and public/.well-known/assetlinks.json')
JSFind your Team ID in your Apple Developer account under Membership details. For the Android fingerprint, eas credentials -p android shows the SHA256 Fingerprint of each build profile's keystore; if Google Play signs your releases, copy the fingerprint from Play Console's app signing page as well. List both, comma separated, so internal builds and store builds both pass.
Run the script. The values below are examples in the right format: replace them with yours.
APPLE_TEAM_ID=ABCDE12345 \
ANDROID_SHA256=0B:30:55:7A:9F:C4:E9:0E:33:58:7D:A2:C7:EC:11:36:5B:80:A5:CA:EF:14:39:5E:83:A8:CD:F2:17:3C:61:86 \
node scripts/write-well-known.mjsCheck it worked
The script prints the two paths it wrote. Look at the iOS file:
cat public/.well-known/apple-app-site-associationIt lists one app ID, ABCDE12345.com.example.larkfield with your values, and two components: /appointments/* and /r/*. Run the script with APPLE_TEAM_ID=abc and it stops with the Team ID message instead of writing a file Apple would reject.
Step 5 · Serve the files with the right headers
Hosting is where these links usually break. The rules: HTTPS with a valid certificate, status 200, no redirect (not even http to https or the bare domain to www), and application/json as the content type. A web server that guesses types from the extension sends the iOS file, which has none, as application/octet-stream. Keep the iOS file under 128 KB.
npx expo export copies public/ into the web build. With the template's server output that is dist/client, so the files end up in dist/client/.well-known/. If the clinic's site is the Expo web build, the files travel with it. If the site runs on another server, copy the two files to its /.well-known/ folder and set the content type there. To see the headers working before you touch the real site, run a small server that does only this. Write it:
cat > scripts/serve-well-known.mjs <<'JS'
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
const files = {
'/.well-known/apple-app-site-association': 'public/.well-known/apple-app-site-association',
'/.well-known/assetlinks.json': 'public/.well-known/assetlinks.json',
}
const port = Number(process.env.PORT ?? 8090)
createServer(async (req, res) => {
const path = new URL(req.url ?? '/', 'http://localhost').pathname
const file = files[path]
if ((req.method !== 'GET' && req.method !== 'HEAD') || !file) {
res.writeHead(404, { 'content-type': 'text/plain' })
res.end('not found\n')
return
}
try {
const body = await readFile(file)
res.writeHead(200, {
'content-type': 'application/json',
'content-length': body.length,
'cache-control': 'max-age=3600',
})
res.end(req.method === 'HEAD' ? undefined : body)
} catch {
res.writeHead(500, { 'content-type': 'text/plain' })
res.end('could not read file\n')
}
}).listen(port, '127.0.0.1', () => console.log(`Serving .well-known on http://127.0.0.1:${port}`))
JSStart it in a second terminal from ~/larkfield-app-demo, and leave it running:
node scripts/serve-well-known.mjsBack in the first terminal, look at the headers the way a verifier sees them:
curl -sI http://127.0.0.1:8090/.well-known/apple-app-site-associationThis asks for the headers only. The first lines are HTTP/1.1 200 OK and content-type: application/json. Node sends header names exactly as the server wrote them, so they are lowercase here; header names are not case-sensitive, so verifiers accept either form.
Check it worked
Headers are only half of it; the body must be valid JSON that names this app. Write a checker that tests status, redirects, content type, size and content against app-links.json. You can point it at the real domain later:
cat > scripts/check-well-known.mjs <<'JS'
import { readFileSync } from 'node:fs'
const base = (process.argv[2] ?? 'http://127.0.0.1:8090').replace(/\/$/, '')
const links = JSON.parse(readFileSync('app-links.json', 'utf8'))
let failed = false
async function check(path, namesThisApp) {
const res = await fetch(base + path, { redirect: 'manual' })
const type = res.headers.get('content-type') ?? ''
const text = await res.text()
const problems = []
if (res.status !== 200) problems.push(`status ${res.status}, needs 200 with no redirect`)
if (!type.startsWith('application/json')) problems.push(`content type "${type}"`)
if (text.length > 128 * 1024) problems.push('larger than 128 KB')
let body
try {
body = JSON.parse(text)
} catch {
problems.push('not valid JSON')
}
if (body && !namesThisApp(body)) problems.push('does not name this app')
console.log(problems.length ? `FAIL ${path}: ${problems.join('; ')}` : `OK ${path}`)
if (problems.length) failed = true
}
await check('/.well-known/apple-app-site-association', (b) =>
(b.applinks?.details ?? []).some((d) => (d.appIDs ?? []).some((id) => id.endsWith(`.${links.iosBundleId}`))),
)
await check('/.well-known/assetlinks.json', (b) =>
Array.isArray(b) && b.some((s) => s.target?.package_name === links.androidPackage),
)
if (base.startsWith('http:')) console.log('Note: Apple and Google only read these files over https.')
process.exitCode = failed ? 1 : 0
JS
node scripts/check-well-known.mjsIt prints OK for both files and the note about https. Once the files are on the clinic's site, run node scripts/check-well-known.mjs https://larkfield.example with your domain. A FAIL line names the problem, for example status 301, needs 200 with no redirect when the site redirects to www.
Step 6 · Rewrite old and short links before they reach a route
Not every link that arrives will be in the shape of your routes. The clinic's old reminder system sent https://larkfield.example/appointment?id=42, and the short SMS links are /r/42. Expo Router lets you rewrite an incoming address in src/app/+native-intent.tsx before it picks a screen. The function there runs outside your React components, so it cannot read the signed-in user, and it must never throw: a crash there is a crash on launch.
Keep the logic in a plain module you can test, and keep the route file thin. The parser avoids URL on purpose: the address may be a full URL, a path or neither, and a hand-written parser behaves the same in Jest and on every phone.
mkdir -p src/linking
cat > src/linking/rewrite.ts <<'TS'
// Appointment IDs are short letters, digits, hyphens and underscores (the mock API issues bk_1). Anything else is not ours.
const ID = /^[A-Za-z0-9_-]{1,64}$/
function splitQuery(route: string): [string, string] {
const i = route.indexOf('?')
return i === -1 ? [route, ''] : [route.slice(0, i), route.slice(i + 1)]
}
function queryValue(query: string, key: string): string | undefined {
for (const pair of query.split('&')) {
const [k, v = ''] = pair.split('=')
if (k !== key) continue
try {
return decodeURIComponent(v.replace(/\+/g, ' '))
} catch {
return undefined
}
}
return undefined
}
// Turns larkfield://appointments/42, https://larkfield.example/appointments/42
// and /appointments/42 into the same route path.
export function toRoutePath(input: string): string {
let rest = input.trim().split('#')[0]
const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(rest)
if (scheme) {
rest = rest.slice(scheme[0].length)
// For web links the host is the clinic's domain, not part of the route.
if (/^https?$/i.test(scheme[1])) rest = rest.replace(/^[^/?]*/, '')
}
const [path, query] = splitQuery(rest)
const clean = ('/' + path).replace(/\/{2,}/g, '/').replace(/(.)\/$/, '$1')
return query ? `${clean}?${query}` : clean
}
export function rewriteIncomingPath(input: string): string {
const route = toRoutePath(input)
const [path, query] = splitQuery(route)
const shortLink = /^\/r\/([^/]+)$/.exec(path)
if (shortLink) return ID.test(shortLink[1]) ? `/appointments/${shortLink[1]}` : '/'
if (path === '/appointment') {
const id = queryValue(query, 'id')
return id && ID.test(id) ? `/appointments/${id}` : '/'
}
const detail = /^\/appointments\/([^/]+)$/.exec(path)
if (detail && !ID.test(detail[1])) return '/'
return route
}
TS
cat > "src/app/+native-intent.tsx" <<'TSX'
import { rewriteIncomingPath } from '@/linking/rewrite'
export function redirectSystemPath({ path }: { path: string; initial: boolean }): string {
try {
return rewriteIncomingPath(path)
} catch {
return '/'
}
}
TSX+native-intent only runs in the iOS and Android apps. On the web, the clinic's server handles old addresses with ordinary redirects. Now the tests, one row per kind of link the clinic sends, plus the ones it should never act on:
cat > src/linking/rewrite.test.ts <<'TS'
import { rewriteIncomingPath } from './rewrite'
describe('rewriteIncomingPath', () => {
test.each([
['larkfield://appointments/42', '/appointments/42'],
['larkfield:///appointments/42', '/appointments/42'],
['https://larkfield.example/appointments/42', '/appointments/42'],
['https://larkfield.example/r/42', '/appointments/42'],
['https://larkfield.example/r/bk_1', '/appointments/bk_1'],
['https://larkfield.example/appointment?id=a1b2', '/appointments/a1b2'],
['/appointments/42/', '/appointments/42'],
['/appointments/42?from=sms', '/appointments/42?from=sms'],
['/appointments', '/appointments'],
['', '/'],
])('%s opens %s', (input, expected) => {
expect(rewriteIncomingPath(input)).toBe(expected)
})
test('sends anything that is not a plain ID to the start screen', () => {
expect(rewriteIncomingPath('https://larkfield.example/r/..%2Fprofile')).toBe('/')
expect(rewriteIncomingPath('larkfield://appointments/%2F%2Fevil.example')).toBe('/')
expect(rewriteIncomingPath('https://larkfield.example/appointment?id=')).toBe('/')
})
})
TSCheck it worked
npx jest src/linking/rewrite.test.tsJest reports 11 passing tests in one suite. Then check that the route file is in the Android bundle and that the web build carries the two files. --no-bytecode and --no-minify keep the bundle readable so you can search it:
npx expo export --platform web --platform android --no-bytecode --no-minify
grep -rl rewriteIncomingPath dist | grep android
ls -A dist/client/.well-knownThe grep prints the path of the Android bundle, somewhere under dist/client/_expo/static/js/android/. Because the template sets web.output to server, the web files land in dist/client, so the listing of dist/client/.well-known shows apple-app-site-association and assetlinks.json. dist is build output; delete it whenever you like.
Step 7 · Let a link wait for sign-in, and let the server decide access
A patient who taps a link while signed out should sign in and then land on the appointment, not on the home tab. And whatever the link says, the ID in it is only a request: anyone can type /appointments/43 into a link. The app may show an appointment only after the server has confirmed it belongs to the signed-in patient.
The waiting part needs one guard: only paths inside the app may be held. Otherwise a crafted link such as ?next=//evil.example turns your sign-in screen into a way to send patients elsewhere. Write the module and its test:
cat > src/linking/held-link.ts <<'TS'
// A path is safe to hold if it stays inside the app: one leading slash, no backslashes.
export function safeNext(next: string | null | undefined): string {
if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return '/'
return next
}
let held: string | null = null
export function holdLink(path: string): void {
const next = safeNext(path)
held = next === '/' ? null : next
}
export function takeHeldLink(): string {
const next = held ?? '/'
held = null
return next
}
TS
cat > src/linking/held-link.test.ts <<'TS'
import { holdLink, safeNext, takeHeldLink } from './held-link'
test('only keeps paths inside the app', () => {
expect(safeNext('/appointments/42')).toBe('/appointments/42')
expect(safeNext('https://evil.example')).toBe('/')
expect(safeNext('//evil.example/x')).toBe('/')
expect(safeNext('/\\evil.example')).toBe('/')
expect(safeNext(undefined)).toBe('/')
})
test('hands a held link over once', () => {
holdLink('/appointments/42')
expect(takeHeldLink()).toBe('/appointments/42')
expect(takeHeldLink()).toBe('/')
})
TS
npx jest src/linkingWhen the app gains sign-in, the layout that guards the patient's screens holds the address and sends the patient to sign in; the sign-in screen hands it back on success. In outline (session is whatever your sign-in code provides):
import { Redirect, usePathname, useRouter } from 'expo-router'
import { holdLink, takeHeldLink } from '@/linking/held-link'
// In the guarding layout:
const pathname = usePathname()
if (!session) {
holdLink(pathname)
return <Redirect href="/sign-in" />
}
// In the sign-in screen:
const router = useRouter()
// ...after the server accepts the patient:
router.replace(takeHeldLink())usePathname() returns the path without its query string, so a held /appointments/42?from=sms comes back as /appointments/42. The appointment screen needs only the ID, so that is fine here; if a screen depends on query values, read them with useGlobalSearchParams() and add them back before holding the link.
Expo Router's Stack.Protected can do the redirect part for you with a guard; you still hold the address yourself so the patient ends up where the link pointed. router.replace matters here: with push, the back button would return to the sign-in screen.
The access check belongs to the API, not the app. In the mock clinic API from part 4 (mock-api/server.mjs), the appointment route answers 404 both when the appointment does not exist and when it belongs to someone else, so a guessed ID tells the guesser nothing. These are its lines; patientId comes from the X-Patient-Id header until the app has real sign-in:
if (req.method === 'GET' && pathname.startsWith('/appointments/')) {
const booking = bookings.get(decodeURIComponent(pathname.slice('/appointments/'.length)))
if (!booking || booking.patientId !== patientId) return send(res, 404, { error: 'not_found' })
return send(res, 200, booking)
}When the detail screen reads appointments from this API, it treats a 404 the way part 1's screen treats an unknown ID, "There is no appointment ...", whatever the reason.
Check it worked
Jest reports two suites and 13 tests passing. Read the 404 rule in your own mock API: a request for another patient's appointment must return the same status and body as a request for an ID that does not exist.
Step 8 · Verify the links with Apple and Google
Upload the two files to the clinic's domain, run node scripts/check-well-known.mjs https://larkfield.example (with your domain) until both lines say OK, then make a new development build so the phone picks up the associated domain and intent filter.
On iOS, install the build and type or paste https://larkfield.example/appointments/42 into Notes or Messages, then tap it. iOS fetches the file through Apple's content delivery network when the app is installed or updated, and does not refresh it often after that. While you are still changing the file, applinks:larkfield.example?mode=developer in associatedDomains makes a device in developer mode fetch it straight from your server; remove ?mode=developer before release.
On Android 12 and later, reset and re-run the verification, wait a minute, and read the result:
adb shell pm set-app-links --package com.example.larkfield 0 all
adb shell pm verify-app-links --re-verify com.example.larkfield
adb shell pm get-app-links com.example.larkfieldUse your package name. Verification needs the phone to be online. If it fails, Android still offers to open the link in the browser, so give the clinic's site a light page at each linked path: the appointment time, the clinic's phone number and a button to get the app. On low-end Android phones and prepaid data, that page should load in a few kilobytes, with no large images or scripts. After you change assetlinks.json, Android 15 and later can take up to seven days to re-check it on patients' phones; older versions only re-check when the app is installed or updated.
The reminders from part 5 already carry the same /appointments/<id> path, so a push notification tap, a text message link and an email link all go through one route and one set of checks.
Check it worked
pm get-app-links lists larkfield.example: verified (your domain) for the package. On both phones, tapping the link in a messaging app opens the appointment screen directly, with no browser page in between. Stop the practice server with Ctrl+C in the second terminal. Keep ~/larkfield-app-demo: the next part tests it.
Next steps
- Cover the screens and the link rewrite with screen tests in test the Larkfield app with Jest and React Native Testing Library.
- Go back over the reminder taps that open the same routes: remind Larkfield patients with local and push notifications.
- Make the builds that carry the new entitlement and intent filter: build and submit an app with EAS.
- Revisit how files become routes: add navigation with Expo Router.
Related tutorials
- Remind Larkfield patients with local and push notifications in ExpoYou will have the Larkfield app schedule reminders 24 hours and 2 hours before each appointment, ask for notification permission only after a booking, cancel reminders with the booking, open the right appointment from a tap, and receive server-sent messages through the Expo push service.
- How to Add Navigation to an Expo App with Expo RouterYou will turn an Expo SDK 58 app into a multi-screen app with Expo Router, using files as routes, a bottom tab bar, a stack of detail screens opened from a list, a dynamic route that reads its parameter, links and navigation from code, and a not-found screen.
- Set up the Larkfield Clinic booking app with Expo Router tabs and stacksYou will have the Larkfield Clinic booking app running in Expo SDK 58, with Book, Appointments and Profile tabs, a Book stack that goes from service to practitioner and time, a typed appointment detail route, shared header styles, in-memory clinic data and a first passing Jest test.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials