Sub topic 15
URLs and deep links on Flutter web
On the web, every URL a user opens is a deep link. Typing an address, following a shared link, and pressing reload all load your app at a specific location. This chapter assumes you have read the go_router chapters and can already map /products/:id to a screen. It covers what changes in the browser: the URL strategy, server configuration, history behavior, and the checks that still apply.
How the web differs from mobile
On Android and iOS, the operating system hands a link to your app through an intent or a user activity. On the web there is no handoff. The browser holds the address, and Flutter reads it when the app boots. Uri.base returns the current page URL, and MaterialApp.router passes it to your router as the initial location.
Three consequences follow:
- Opening a link and reloading the page are both a cold start. Your app starts from nothing and must rebuild its state from the URL.
- There is no
assetlinks.jsonor Associated Domains setup for the web app itself. The domain is the app. - The browser's back and forward buttons are part of your navigation model, so they must behave sensibly.
Choosing a URL strategy
Flutter web supports two URL strategies.
| Strategy | Example URL | Server setup | Notes |
|---|---|---|---|
| Hash (default) | `https://example.com/#/products/42` | None | The route lives after `#`, which the browser never sends to the server. |
| Path | `https://example.com/products/42` | Rewrite all paths to `index.html` | Clean URLs that look like your mobile links. |
Use the path strategy when you want one URL to work on web, Android, and iOS. Call usePathUrlStrategy() before runApp. On mobile the call does nothing, so you do not need to guard it.
Add flutter_web_plugins to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
go_router: ^14.0.0Then write a small app that uses it:
import 'package:flutter/material.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'package:go_router/go_router.dart';
void main() {
usePathUrlStrategy();
runApp(const MyApp());
}
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/products/:id',
builder: (context, state) =>
ProductScreen(id: state.pathParameters['id']!),
),
],
errorBuilder: (context, state) => NotFoundScreen(uri: state.uri),
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Shop',
routerConfig: router,
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: FilledButton(
onPressed: () => context.go('/products/42?ref=home'),
child: const Text('Open product 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Showing product $id')),
);
}
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, required this.uri});
final Uri uri;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('No page at $uri')),
);
}
}Run it with flutter run -d chrome. Press the button, and the address bar changes to /products/42?ref=home. Reload the page and you land on the same screen.
Configuring the server
With the path strategy, a reload at /products/42 sends a real request for that path. A static file server has no such file, so it returns a 404 and your app never starts. The fix is to serve index.html for any path that is not a real file.
On Firebase Hosting, add a rewrite to firebase.json:
{
"hosting": {
"public": "build/web",
"rewrites": [
{ "source": "**", "destination": "/index.html" }
]
}
}On nginx, use try_files:
location / {
root /var/www/app;
try_files $uri $uri/ /index.html;
}The dev server started by flutter run already does this, so a missing rewrite only shows up after you deploy. Test a production build before you ship.
Hosting under a sub-path
If the app lives at https://example.com/app/, the browser must resolve asset URLs relative to that path. Build with a base href:
flutter build web --base-href /app/The value must start and end with a slash. Your routes stay /products/:id, and the browser shows /app/products/42.
Verification files on the same domain
Your web app and your mobile verification files can share one domain. Put assetlinks.json and apple-app-site-association in web/.well-known/. Flutter copies them to build/web/.well-known/. Two things commonly break this:
- Your rewrite rule or host may catch these paths. Static files should win over the rewrite, but check by requesting each file and confirming it returns JSON, not your app's HTML.
- Some hosts ignore dot-directories by default. Firebase Hosting lists
**/.*underignore, which does not hide.well-known, but a custom ignore list may.
History, back, and the address bar
go_router reports each location to the browser's history, so the back and forward buttons work. The method you choose decides what history looks like:
context.go('/products/42')replaces the current stack with the matched routes. The user can go back to a parent only if the route tree defines one.context.push('/products/42')adds an entry on top. Back returns to the previous page.
Recent go_router versions have changed how URLs reflect imperative push calls, so read the changelog for the version you pin. If the address bar must always match the visible screen, prefer go and nested routes over push.
Browser-specific places a router also matters:
- A shared link is a cold start, so any state your screen needs must be loadable from the path and query. Do not rely on
extra, which is lost on reload and in a pasted link. - The tab title does not follow your route automatically. Wrap screens in the
Titlewidget to set it. - Flutter web draws to a canvas, so search crawlers see little of your content. Deep links work for users, but they do not give you search indexing.
Security on the web
Anything in the address bar is user input. The validation rules from the security chapter apply unchanged:
- Parse path parameters before use, for example
int.tryParse(id), and show the fallback screen when parsing fails. - Check redirect targets. A login flow that returns to
?from=...must accept only paths inside your app, not full URLs to other sites. - Never put tokens or secrets in the URL. They end up in browser history, server logs, and the
Refererheader.
The hash strategy hides the route from the server, but it does not make the URL safer. The user, extensions, and shared links still see it.
Checking your work
You can test web deep links without any device tooling. Open http://localhost:PORT/products/42 directly in a new tab, then reload, then use back and forward. Also try /products/ and /nonsense to confirm that the fallback screen appears. After deploying, repeat the same checks on the real domain, since rewrites only exist there.
Exercise
You switch a Flutter web app to usePathUrlStrategy(). It works with flutter run -d chrome, but after deploying to a static host, opening https://example.com/products/42 shows a 404 page, while https://example.com/ works. What is wrong, and what do you change?
Show answer
The server looks for a file at /products/42, finds none, and returns 404, so Flutter never starts. The dev server rewrites unknown paths to index.html, which hid the problem locally. Add a rewrite on the host that serves /index.html for every path that is not a real file, for example { "source": "**", "destination": "/index.html" } in firebase.json or try_files $uri $uri/ /index.html; in nginx. The router then reads /products/42 from the browser URL after the app boots.
Exercise
A product screen is opened with context.push('/checkout', extra: cart). Users report that reloading the page, or opening a copied link, shows an error. Why does this happen, and how would you fix it?
Show answer
extra exists only in memory for the current session. A reload or a pasted link is a cold start that has only the URL, so state.extra is null. Put the identifying data in the path or query, such as /checkout?cartId=abc, and load the cart from that ID in the screen or a redirect. Keep extra for optional hints that the screen can work without.