<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Neeraj Deolekar on Medium]]></title>
        <description><![CDATA[Stories by Neeraj Deolekar on Medium]]></description>
        <link>https://medium.com/@neerajdeolekar?source=rss-bcfbb24888b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3vuzXtJqmu6sgPaf.jpg</url>
            <title>Stories by Neeraj Deolekar on Medium</title>
            <link>https://medium.com/@neerajdeolekar?source=rss-bcfbb24888b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:48:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neerajdeolekar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building AI Assistants From Scratch Is Dead. Here’s What’s Replacing It.]]></title>
            <link>https://medium.com/@neerajdeolekar/building-ai-assistants-from-scratch-is-dead-heres-what-s-replacing-it-ed6d084b8cf6?source=rss-bcfbb24888b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed6d084b8cf6</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[product-design]]></category>
            <dc:creator><![CDATA[Neeraj Deolekar]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 16:22:33 GMT</pubDate>
            <atom:updated>2026-07-28T16:22:33.779Z</atom:updated>
            <content:encoded><![CDATA[<p>We kept making the same mistake.</p><p>Every time a new client came along with a new domain, we’d start a new personal assistant project. New prompts, new memory system, new context plumbing, new rules to keep the thing from going off the rails. And then three months later we’d do it all over again for someone else. Different industry, same grind.</p><p>At some point, probably around the third or fourth time, it hit us that most of what makes a personal assistant or chatbot actually useful has nothing to do with the domain. The hard part isn’t teaching it about transit schedules or financial regulations or whatever the client cares about. The hard part is getting it to understand the person on the other end. Remembering what they told you last week. Noticing that they always phrase things a certain way when they’re frustrated. Figuring out whether “just do it” means they’ve made a decision or they’re venting.</p><p>That stuff is universal. A nurse and a city planner and a logistics manager all benefit from an assistant that actually knows them.</p><p>So we stopped rebuilding it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wb5RUG4OdAVRXDLJiJQumw.png" /><figcaption>Figure 1. User Intelligence: A reusable AI layer powering personalized AI assistants across multiple business domains.</figcaption></figure><h3>What we actually built</h3><p>We pulled out everything that’s about understanding the user and packaged it as its own layer. We call it a user intelligence layer, which sounds fancy, but the idea is simple: it’s the part of the system that models the person, not the product.</p><p>Here’s what that means in practice. The layer keeps a picture of each user across sessions. Not a raw dump of old messages, more like a curated understanding of what they care about, what they’ve decided, what constraints they’re working under. It picks up on working style over time. If someone always wants options laid out before making a call, it learns that. If someone just wants the answer, it learns that too.</p><p>One thing we think is genuinely different about how we did this: the system doesn’t just quietly act on what it thinks it knows. It proposes. It says, roughly, “I think this is the goal you’re pursuing” or “it looks like you just set this boundary,” and then the person confirms or pushes back. That loop matters more than it might sound. Without it, you get an assistant that slowly drifts on stale assumptions, and nobody notices until it does something weird.</p><p>There’s also a decay mechanism. Patterns that haven’t shown up in a while lose confidence over time. So the model of a person reflects who they are now, not who they were six months ago when they first started using the thing. We won’t pretend the decay tuning was easy to get right, but the principle is sound, and it makes a real difference.</p><h3>Why this isn’t just “an assistant with memory”</h3><p>We get this pushback sometimes. “So you gave the assistant a longer memory, what’s the big deal?”</p><p>The difference is structure. A long context window or a retrieval system over old messages gives you access to information. You can look things up. But that’s not the same as maintaining typed knowledge about someone’s goals, their constraints, their emotional state, with rules about what’s confirmed versus inferred, what’s strengthening versus fading. A document search can tell you what someone said on Tuesday. It can’t tell you that they’ve been gradually shifting their priorities over the past month and the thing they asked for today doesn’t match what they actually need.</p><p>Maybe that sounds abstract. The concrete version: when the intelligence layer is working well, the assistant adjusts without being asked. A frustrated question gets a shorter, more direct answer. An exploratory question gets options. A request that contradicts something the person committed to last week gets a gentle flag, not silent compliance. None of that comes from retrieval. It comes from maintaining a living model.</p><h3>The MCP trick</h3><p>Okay, so we have this user intelligence layer. How does it actually connect to anything?</p><p>This is where Model Context Protocol comes in. MCP, if you haven’t bumped into it yet, is basically a standard way to connect AI assistants to external tools and data sources. Think of it like USB for AI: you expose something as an MCP server, and any MCP-compatible system can talk to it. No custom integration code for every new data source.</p><p>We made our intelligence layer MCP-native. And then the insight was: the domain knowledge can arrive the same way. You want the assistant to know about your product? Wire up an MCP server with your knowledge base. Want it to query live data? Wire up another one for your database. Plug them in alongside the intelligence layer, and you’re done.</p><p>We’re oversimplifying a bit; there’s scope tuning and some guardrail work involved, but the core idea really is that simple. The brain stays the same. You swap the stuff around it.</p><h3>We tried it for real</h3><p>We didn’t want this to be one of those “here’s a nice architecture diagram, trust us it works” situations. So we built an actual assistant for an urban mobility platform. We’ll call it CityFlow here since the real client prefers not to be named.</p><p>CityFlow is the kind of portal a city runs to manage transit and fleet operations. People using it, both city staff and residents, have questions all the time. How does this feature work? What’s the policy on X? What’s the current status of Y?</p><p>We plugged in two MCP servers.</p><p>First, a knowledge base server. This one grounds the assistant in CityFlow’s actual documentation. And grounding turned out to be even more important than we expected, because without it, the model would confidently answer questions about things the portal doesn’t even do. With the knowledge base, if someone asks about something outside the domain, the assistant says it doesn’t know. For a public-facing city service, that honesty is worth more than cleverness.</p><p>Second, a database server. This gives the assistant access to live, structured data, the kind of stuff that changes daily and can’t live in static docs.</p><p>The whole thing came together in about two weeks. A from-scratch build for something like this would’ve taken us at least two months, probably more. And the part that made it fast wasn’t any single technical trick. It was that we didn’t have to rebuild the understanding-the-user part at all. That was just there, already working.</p><h3>The part we didn’t expect</h3><p>What surprised us wasn’t that the architecture worked. We’d designed it to work this way.</p><p>What surprised us was how little of the per-client work was engineering. Most of it was content. Curating the knowledge base, setting the scope so the assistant knows its boundaries, testing edge cases where it might wander. That’s important work, but it’s a fundamentally different kind of work than writing code. It means a new domain doesn’t need a new engineering sprint. It needs a subject matter expert and a couple of weeks.</p><p>And because every instance runs on the same intelligence layer, when we improve something in the core, like better intent detection or more nuanced emotional context, every client gets it. We don’t have to port fixes across five different assistant codebases.</p><h3>What we’d tell someone starting from scratch</h3><p>If you’re building an AI assistant and you’re thinking about the domain first, you might be solving things in the wrong order. The domain is the easy part, relatively speaking. You can always teach a system new facts. Teaching it to actually understand a person is the harder problem, and it’s the one that doesn’t change between clients.</p><p>Separate those two things early. Build the user understanding once, build it well, and make it pluggable. Let a protocol like MCP handle the seam between the brain and the domain knowledge. You’ll thank yourself the second time a new use case shows up, and you don’t have to start over.</p><p>CityFlow was our first real test of this approach. It won’t be the last.</p><p>If you’re wrestling with the same problem- building assistants that feel intelligent across different domains without rebuilding from zero each time- we’d be glad to compare notes. Reach out or drop a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed6d084b8cf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of GraphQL Subscriptions for Your Private Domain in Flutter Android…]]></title>
            <link>https://medium.com/@neerajdeolekar/unlocking-the-power-of-graphql-subscriptions-for-your-private-domain-in-flutter-android-c10a10bee074?source=rss-bcfbb24888b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10a10bee074</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Neeraj Deolekar]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 10:48:11 GMT</pubDate>
            <atom:updated>2026-07-24T10:48:11.206Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking the Power of GraphQL Subscriptions for Your Private Domain in Flutter Android Application: A Journey with Self-Signed Certificates, Hasura Engine, WebSockets and Keycloak!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiSs2-SwkzFFIf43l9vS4g.png" /></figure><p>Explore the realm of real-time data with GraphQL subscriptions while ensuring secure connections using self-signed certificates. Learn how to take advantage of the Hasura Engine’s existing capabilities alongside Keycloak’s robust authentication features to enhance your application’s performance and security. Join us as we explore this innovative implementation that enhances the functionalities of your private domain!</p><p>In my previous article, I discussed using Hasura Subscriptions to retrieve real-time data from a database. However, the SSL certificate we used was not for a private domain; it was generated with the OpenSSL certificate generator. In my actual project, we were using a private domain with a self-signed certificate used in a Flutter Android application. The main issue with using Hasura Subscriptions in this context is that a WebSocket connection cannot be established due to the inability to validate the self-signed certificate for the private domain. After extensive research, I discovered that graphql_flutter&#39;s WebSocketLink does not work out of the box with self-signed certificates on private domains, leading to the error message &quot;CERTIFICATE_VERIFY_FAILED&quot; or &quot;hostname is not resolved.&quot;</p><p>Here is the previous article: <a href="https://medium.com/@neerajdeolekar/how-to-implement-graphql-subscription-using-the-existing-hasura-engine-and-keycloack-authentication-e8ecbcfe039c">Flutter: How to implement GraphQL subscription using the existing Hasura engine and Keycloak authentication?</a></p><h3>The Real Problem Nobody Tells You About</h3><p>When you first hit that CERTIFICATE_VERIFY_FAILED error, the natural instinct is to Google it, find a Stack Overflow thread, and try a few certificate bypass tricks. I did the same. What I found is that graphql_flutter&#39;s WebSocketLink has no direct HttpClient or SecurityContext parameter in its constructor. Without that, there is no obvious way to inject certificate trust for your self-signed PEM file.</p><p>The standard approach everyone shows looks like this, and this is intentionally commented out in the codebase to explain exactly where it falls short:</p><pre>// This does NOT work with self-signed certs on a private domain<br>// final WebSocketLink webSocketLink = WebSocketLink(<br>//   EnvConstants.webSocketGraphqlUrl,<br>//   config: SocketClientConfig(<br>//     autoReconnect: _isLoggedIn.value,<br>//     initialPayload: () async =&gt; {<br>//       &#39;headers&#39;: {&#39;Authorization&#39;: &#39;Bearer $accessToken&#39;},<br>//     },<br>//     delayBetweenReconnectionAttempts: const Duration(seconds: 10),<br>//     onConnectionLost: (code, reason) async { ... },<br>//   ),<br>// );</pre><p>The moment you switch to a wss:// endpoint on a private domain with a self-signed cert, this fails with no useful error. No log, just a connection that never completes.</p><p>What I initially missed — and what the library does not make obvious — is that SocketClientConfig has a connectFn parameter that acts as an official escape hatch. It lets you take full control of how the WebSocket connection is established, including injecting your own HttpClient with a custom SecurityContext. I discovered this only after I had already built a full raw WebSocket bypass. Both approaches work and are covered below.</p><h3>Two Approaches, One Problem</h3><p>Before jumping into code, here is a quick map of the two paths:</p><p><strong>Approach 1: connectFn inside WebSocketLink (recommended)</strong> Stays within graphql_flutter. Keeps auto-reconnect, subscription lifecycle management, and widget integration working. Uses SocketClientConfig.connectFn to inject certificate trust. Cleaner and less code to maintain.</p><p><strong>Approach 2: Raw dart:io WebSocket bypass (alternative)</strong> Drops below WebSocketLink entirely and builds the connection manually using dart:io&#39;s WebSocket.connect(). Gives full control but loses all WebSocketLink features - you are responsible for reconnection, lifecycle, and message routing yourself.</p><p>Both are validated and working. Approach 1 is where you should start.</p><h3>Step 1: Bundle Your PEM Certificate as an Asset</h3><p>This step is the same regardless of which approach you take. Drop your self-signed PEM file into assets/certs/ and declare it in pubspec.yaml. Without this declaration, rootBundle.load() will throw at runtime.</p><p>The fix is to drop down one level below WebSocketLink and use dart:io&#39;s WebSocket.connect() directly, with a custom HttpClient that carries your bundled certificate. Then you wrap that raw socket in an IOWebSocketChannel to get the familiar stream-sink interface back.</p><p>Here is the full WebSocket flow, step by step:</p><pre># pubspec.yaml<br>flutter:<br>  assets:<br>    - assets/certs/book_ssl_key.pem<br>    - assets/certs/book_ssl_key_uat.pem</pre><p>Having separate certs for UAT and production is worth the small overhead. You do not want to ship a UAT cert to the Play Store accidentally.</p><h3>Approach 1: The connectFn Escape Hatch (Recommended)</h3><p>SocketClientConfig exposes a connectFn parameter typed as:</p><pre>typedef WebSocketConnect = FutureOr&lt;WebSocketChannel&gt; Function(<br>  Uri uri,<br>  Iterable&lt;String&gt;? protocols,<br>);</pre><p>This lets you replace the default connection behaviour with your own — including a custom HttpClient carrying your self-signed certificate. The result is still a proper WebSocketLink, so everything in graphql_flutter continues to work normally.</p><pre>import &#39;dart:io&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br>import &#39;package:web_socket_channel/io.dart&#39;;<br><br>Future&lt;WebSocketLink&gt; buildSecureWebSocketLink(String url) async {<br>  final pemBytes = (await rootBundle.load(&#39;assets/certs/book_ssl_key_uat.pem&#39;))<br>      .buffer<br>      .asUint8List();<br><br>  // Note: connectFn is marked experimental in graphql_flutter docs.<br>  // Behaviour may change in future minor versions - pin your version accordingly.<br>  return WebSocketLink(<br>    url,<br>    config: SocketClientConfig(<br>      autoReconnect: true,<br>      connectFn: (uri, protocols) {<br>        final httpClient = HttpClient(<br>          context: SecurityContext(withTrustedRoots: false)<br>            ..setTrustedCertificatesBytes(pemBytes),<br>        )..badCertificateCallback =<br>            (X509Certificate cert, String host, int port) =&gt;<br>                host == EnvConstants.hostname;<br><br>        return IOWebSocketChannel.connect(<br>          uri,<br>          protocols: protocols,<br>          customClient: httpClient,<br>          // Pass auth headers here, inside connectFn<br>          headers: {<br>            &#39;Authorization&#39;: &#39;Bearer $accessToken&#39;,<br>          },<br>        );<br>      },<br>    ),<br>  );<br>}</pre><blockquote><strong>Critical gotcha on headers:</strong> When connectFn is provided, the headers field on SocketClientConfig is silently bypassed by the library. If you pass your Bearer token via SocketClientConfig(headers: {...}) alongside a connectFn, it will never reach the connection. Always pass headers directly inside IOWebSocketChannel.connect() within your connectFn instead.</blockquote><p>The wss:// endpoint and hostname live in .env.uat, loaded at runtime via flutter_dotenv:</p><pre>WEB_SOCKET_GRAPH_QL_URL=wss://myapp.example.local/v1/graphql<br>HOST_NAME=myapp.example.local</pre><blockquote><strong>Note on Android:</strong> There is no network_security_config.xml involved here. The certificate trust is handled entirely in Dart through SecurityContext. This is the correct production approach. You are not weakening Android&#39;s network security policy at the OS level; you are teaching your app&#39;s own HTTP stack to trust a specific certificate.</blockquote><h3>Approach 2: Raw dart:io WebSocket Bypass (Alternative)</h3><p>If you need absolute control — or if connectFn&#39;s experimental status makes you uncomfortable for a production app - you can drop below WebSocketLink entirely and manage the WebSocket connection yourself using dart:io.</p><p>The trade-off is that you take on responsibility for reconnection, subscription lifecycle, and message routing that WebSocketLink would otherwise be handled for you. Here is the implementation:</p><pre>// lib/src/auth_controller.dart<br>Future&lt;WebSocket&gt; _connectSocket() async {<br>  final cert = await rootBundle.load(&#39;assets/certs/book_ssl_key_uat.pem&#39;);<br>  final context = SecurityContext(withTrustedRoots: false);<br>  context.setTrustedCertificatesBytes(cert.buffer.asInt8List());<br><br>  final httpClient = HttpClient(context: context)<br>    ..badCertificateCallback =<br>        (X509Certificate cert, String host, int port) =&gt; host == EnvConstants.hostname;<br><br>  return WebSocket.connect(<br>    EnvConstants.webSocketGraphqlUrl,<br>    customClient: httpClient,<br>  );<br>}</pre><p>Once the raw socket is open, wrap it in IOWebSocketChannel and send connection_init with the Keycloak JWT. This is how Hasura authenticates the WebSocket session - it validates the JWT against your Keycloak configuration before allowing any subscriptions through:</p><pre>// lib/src/auth_controller.dart<br>Future&lt;void&gt; connect() async {<br>  if (_isLoggedIn.value) {<br>    try {<br>      var accessToken = await secureStorage?.read(key: &#39;accessToken&#39;) ?? &#39;&#39;;<br>      final socket = await _connectSocket();<br>      _channel = IOWebSocketChannel(socket);<br>      _listen();<br>      _channel.sink.add(jsonEncode({<br>        &quot;type&quot;: &quot;connection_init&quot;,<br>        &quot;payload&quot;: {<br>          &quot;headers&quot;: {&quot;Authorization&quot;: &quot;Bearer $accessToken&quot;}<br>        }<br>      }));<br><br>      // Flush any messages queued before the connection was ready<br>      for (var msg in _messageQueue) {<br>        _channel.sink.add(jsonEncode(msg));<br>      }<br>      _messageQueue.clear();<br>    } catch (e) {<br>      debugPrint(&quot;Connection error: $e&quot;);<br>      _scheduleReconnect();<br>    }<br>  }<br>}</pre><p>The message queue is a small but important detail. If anything in the app tries to start a subscription before the WebSocket is fully open, the message is parked and flushed here instead of being silently dropped.</p><h3>Handling JWT Expiry Without Disrupting the User</h3><p>This applies to both approaches. Hasura is strict about expired tokens on WebSocket connections. When the JWT expires, it closes the socket with a close code 4400 and a reason string that looks like this:</p><pre>{&quot;server_error_msg&quot;:&quot;4400: Connection initialization failed: Could not verify JWT: JWTExpired&quot;}</pre><p>The error handler catches this specific case, silently refreshes the token via Keycloak, and reconnects:</p><pre>// lib/src/auth_controller.dart<br>onError: (err) async {<br>  if (_channel.closeCode == 4400 || _channel.closeCode == 1005) {<br>    if (_isLoggedIn.value &amp;&amp; (<br>      _channel.closeCode == 1005 ||<br>      _channel.closeReason == &#39;{&quot;server_error_msg&quot;:&quot;4400: Connection initialization failed: Could not verify JWT: JWTExpired&quot;}&#39;<br>    )) {<br>      await authService.getAccessToken(); // silent refresh via Keycloak<br>    }<br>  }<br>  _scheduleReconnect();<br>},</pre><p>The token refresh exchanges the stored refreshToken with the Go backend, which calls Keycloak. If the refresh fails, the user is sent back to the login screen:</p><pre>// lib/src/services/auth_service.dart<br>Future&lt;void&gt; getAccessToken() async {<br>  var refreshToken = await secureStorage?.read(key: &#39;refreshToken&#39;) ?? &#39;&#39;;<br>  var dio = await getDio();<br>  var response = await dio.post(<br>    EnvConstants.goUrl + UrlConstants.getAccessToken,<br>    data: {&#39;refresh_token&#39;: refreshToken},<br>  );<br>  if (response.statusCode == 200) {<br>    KeyCloakResponse res = KeyCloakResponse.fromJson(response.data);<br>    await secureStorage?.write(key: &#39;accessToken&#39;, value: res.accessToken ?? &#39;&#39;);<br>    await secureStorage?.write(key: &#39;refreshToken&#39;, value: res.refreshToken ?? &#39;&#39;);<br>  } else {<br>    await removeSharedPref();<br>    Get.offAllNamed(&#39;/login&#39;); // kick to login if refresh fails<br>  }<br>}</pre><h3>Routing Incoming Data to the Right Subscriber</h3><p>The _listen() method sits on the incoming stream and routes each message to the correct handler based on the subscription id. When a data frame arrives, the corresponding ValueNotifier&lt;SubscriptionState&lt;T&gt;&gt; is updated, and every widget observing it rebuilds automatically.</p><p>A central registry in AuthController manages the state for all active subscriptions:</p><pre>// lib/src/auth_controller.dart<br>ValueNotifier&lt;SubscriptionState&lt;T&gt;&gt; getSubscriptionState&lt;T&gt;(String id) {<br>  return _subscriptionStates.putIfAbsent(<br>    id,<br>    () =&gt; ValueNotifier&lt;SubscriptionState&lt;T&gt;&gt;(SubscriptionState&lt;T&gt;(isLoading: true)),<br>  ) as ValueNotifier&lt;SubscriptionState&lt;T&gt;&gt;;<br>}</pre><p>On the UI side, a ValueListenableBuilder observes the notifier:</p><pre>// lib/src/screens/book_details/book_details_view.dart<br>final stateNotifier = bookDetailsController<br>    .authController<br>    .getSubscriptionState&lt;Subscription$get_book_details&gt;(&quot;book_details&quot;);<br><br>return ValueListenableBuilder&lt;SubscriptionState&lt;Subscription$get_book_details&gt;&gt;(<br>  valueListenable: stateNotifier,<br>  builder: (context, messages, _) {<br>    if (messages.error != null) {<br>      return Center(child: Text(ApiConstants.noDataFound));<br>    }<br>    if (messages.isLoading) {<br>      return const Center(child: CircularProgressIndicator(color: Colors.blueAccent));<br>    }<br>    if (messages.data == null) {<br>      return Center(child: Text(ApiConstants.noDataFound));<br>    }<br>    bookDetailsController.setBookDetailsData(messages.data!);<br>    return Obx(() =&gt; Stack(...));<br>  },<br>);</pre><p>Subscription$get_book_details is a typed Dart class generated by graphql_codegen from your .graphql subscription file. No manual json[&#39;field&#39;] digging in the UI layer.</p><h3>Cleaning Up When the Screen Closes</h3><p>When a screen that owns a subscription is disposed, send a stop message over the WebSocket to tell Hasura to stop streaming data for that subscription ID. Without this, Hasura keeps streaming and wastes both server resources and battery.</p><pre>// lib/src/screens/book_details/book_details_controller.dart<br>@override<br>void onClose() {<br>  authController.activeSubscriptionIds.remove(&quot;book_details&quot;);<br>  authController.send({<br>    &quot;id&quot;: &quot;book_details&quot;,<br>    &quot;type&quot;: &quot;stop&quot;<br>  });<br>  super.onClose();<br>}</pre><p>On logout, full cleanup happens via disconnect():</p><pre>// lib/src/auth_controller.dart<br>void disconnect() {<br>  closeAllSubscriptions(); // sends &quot;stop&quot; for every active subscription ID<br>  _subscription?.cancel();<br>  _subscription = null;<br>  _channel.sink.close();   // closes the underlying WebSocket<br>}</pre><h3>SSL Pinning for HTTP Queries and REST Calls</h3><p>The same SecurityContext pattern applies to HttpLink for GraphQL queries and mutations, and to Dio for REST calls. The IOClient wrapper from the http package accepts a custom HttpClient:</p><pre>// lib/src/services/ssl_certification_validation_service.dart<br>Future&lt;IOClient&gt; createHttpClient() async {<br>  final sslCert = await rootBundle.load(&#39;assets/certs/book_ssl_key_uat.pem&#39;);<br>  final securityContext = SecurityContext(withTrustedRoots: false);<br>  securityContext.setTrustedCertificatesBytes(sslCert.buffer.asInt8List());<br><br>  final httpClient = HttpClient(context: securityContext);<br>  httpClient.badCertificateCallback =<br>      (X509Certificate cert, String host, int port) =&gt;<br>          host == EnvConstants.hostname;<br><br>  return IOClient(httpClient);<br>}</pre><p>The same PEM file and badCertificateCallback pattern runs in three places: the WebSocket connection, HttpLink for GraphQL queries, and Dio for REST calls. Consistent security handling across all network layers.</p><p>The NullLink prevents any accidental unauthenticated requests when the user is not logged in:</p><pre>// lib/src/utils/graphql_client_link.dart<br>class NullLink extends Link {<br>  @override<br>  Stream&lt;Response&gt; request(Request request, [forward]) {<br>    return const Stream.empty();<br>  }<br>}</pre><h3>Complete Architecture at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9eDV32Wx397zjFadwqKHw.png" /></figure><h3>Packages Used</h3><pre>dependencies:<br>  graphql_flutter: ^5.1.2       # GraphQLClient, HttpLink, AuthLink, WebSocketLink<br>  gql: ^1.0.1-alpha             # GraphQL document parser<br>  web_socket_channel: ^3.0.3    # IOWebSocketChannel wrapper<br>  http: ^1.2.2                  # IOClient (SSL-pinned HttpLink)<br>  dio: ^5.5.0+1                 # REST calls to Go backend<br>  flutter_secure_storage: ^9.2.2<br>  jwt_decoder: ^2.0.1           # Decode Keycloak JWTs<br>  flutter_dotenv: ^5.1.0        # Runtime env config<br><br>dev_dependencies:<br>  build_runner: ^2.4.11<br>  graphql_codegen: ^0.14.0      # Generates typed Dart classes from .graphql files</pre><blockquote><strong>Android note:</strong> graphql_flutter 5.x requires Java 17 and Gradle 8.4. If you are upgrading from 4.x, update android/gradle/wrapper/gradle-wrapper.properties to gradle-8.4-bin.zip and set JavaVersion.VERSION_17 in your build.gradle compile options.</blockquote><h3>Closing Thoughts</h3><p>Here is the honest version of the journey: I solved this problem the hard way first. I assumed WebSocketLink was a black box with no way through and built the entire raw WebSocket layer from scratch. It worked. Then, while validating the article before publishing, I found that SocketClientConfig.connectFn had been the official escape hatch all along - available since graphql_flutter v4.1.0.</p><p>Both paths are valid. If you are starting fresh, use connectFn - it is less code and keeps you inside the graphql_flutter ecosystem. If you need absolute control over the connection lifecycle or connectFn&#39;s experimental status concerns you for a production app, the raw dart:io bypass is a solid alternative.</p><p>The one thing both approaches share: the SecurityContext pattern with a bundled PEM file and a hostname-scoped badCertificateCallback. That is the actual key to making self-signed certificates work in Flutter on Android, regardless of which WebSocket layer sits on top.</p><p><em>If you found this helpful, feel free to leave a comment or connect on Medium. The previous article covering the non-private-domain setup is linked at the top. Reading both in order gives you the full picture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10a10bee074" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: How to implement GraphQL subscription using the existing Hasura engine and Keycloack…]]></title>
            <link>https://medium.com/@neerajdeolekar/how-to-implement-graphql-subscription-using-the-existing-hasura-engine-and-keycloack-authentication-e8ecbcfe039c?source=rss-bcfbb24888b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8ecbcfe039c</guid>
            <category><![CDATA[graphql-subscriptions]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[hasura]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Neeraj Deolekar]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 12:53:10 GMT</pubDate>
            <atom:updated>2025-05-24T11:01:47.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter: How to implement GraphQL subscription using the existing Hasura engine and Keycloack authentication?</h3><p>While working on a project, we had a use case for implementing live data streaming using GraphQL subscriptions; I was facing some issues and problems regarding setting up the WebSocket link for connecting the Hasura engine with Keycloack authentication. The basic errors were related to invalid JWT tokens, the token expired, and subscriptions must select one top-level field.</p><p>After researching this for a couple of days and not getting a complete solution by using a single source, I am writing this blog to solve all the mentioned issues in a single blog. Using this article, you will learn the correct implementation of a subscription in your Flutter app for live data streaming.</p><h3>Prerequisites:</h3><ul><li>Running Hasura engine</li><li>Running Keycloack service</li><li>A good knowledge of flutter</li><li>A good understanding of GraphQL</li><li>To get the GraphQL schema first we need to install the npm and if you have it already, install the package using the below command.</li></ul><pre>$ npm i get-graphql-schema</pre><p>Now, you can get the schema using the below command.</p><pre>$ get-graphql-schema -h {your x-hasura admin credentials} {your domain name} &gt; schema.graphql</pre><p>Example:</p><pre>$ get-graphql-schema -h x-hasura-admin-secret=localdev https://sankey.hoc-dev.agilrad.com/jwt/v1/graphql &gt; schema.graphql</pre><blockquote><strong>What is a subscription in GraphQL?</strong><br>Subscriptions in GraphQL enable real-time data streaming. They establish a continuous connection between the client and the server, allowing the server to push new information to the client as soon as it becomes available. It’s like getting live notifications about changes to your data.</blockquote><h3>Integrate GraphQL in Flutter</h3><p>First of all, we need to add a GraphQL library in Flutter.</p><ul><li>Add the following packages in your pubspec.yaml file</li></ul><pre>graphql_flutter: latest<br>graphql: latest<br>gql: latest<br>build_runner: latest<br>graphql_codegen: latest<br>get: latest</pre><ul><li>Run the following command to install the packages</li></ul><pre>$ flutter pub get</pre><ul><li>Now let’s create a client for Graphql. Here there are two steps to create a GraphQL client for the subscription.</li></ul><p>Step 1: Create an HTTP link to connect our Hasura engine using the graphql_flutter package.</p><p>Step 2: Create a WebSocket link to listen to any changes that occur in the database.</p><p>Here is the code snippet for the same.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:get/get.dart&#39;;<br>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br>import &#39;package:flutter_secure_storage/flutter_secure_storage.dart&#39;;<br><br>class GraphqlAuthController extends GetxController {<br>  final RxBool _isLoggedIn = false.obs;<br>  late ValueNotifier&lt;GraphQLClient&gt; _client;<br><br>  bool get isLoggedIn =&gt; _isLoggedIn.value;<br>  ValueNotifier&lt;GraphQLClient&gt; get client =&gt; _client;<br><br>  @override<br>  void onInit() async {<br>    await getGraphQLClient();<br>    super.onInit();<br>  }<br><br>  @override<br>  void onClose() {<br>    _isLoggedIn.close();<br>    super.onClose();<br>  }<br><br>  Future&lt;void&gt; onLogin() async {<br>    _isLoggedIn.value = true;<br>    _isLoggedIn.refresh();<br>    await getGraphQLClient();<br>  }<br><br>  Future&lt;void&gt; onLogout() async {<br>    _isLoggedIn.value = false;<br>    _isLoggedIn.refresh();<br>    await getGraphQLClient();<br>  }<br><br>  Future&lt;void&gt; getGraphQLClient() async {<br>    try {<br>      var accessToken = await secureStorage?.read(key: &#39;accessToken&#39;) ?? &#39;&#39;;<br>      final HttpLink httpLink = HttpLink(<br>        &#39;https://test.hoc-dev.agilrad.com/jwt/v1/graphql&#39;<br>      );<br>      final AuthLink authLink = AuthLink(getToken: () async =&gt; &#39;Bearer $accessToken&#39;);<br>      final Link httpAuthLink = authLink.concat(httpLink as Link);<br><br>      final WebSocketLink webSocketLink = WebSocketLink(<br>        &#39;wss://test.hoc-dev.agilrad.com/jwt/v1/graphql&#39;,<br>        config: SocketClientConfig(<br>          autoReconnect: _isLoggedIn.value,<br>          initialPayload: () async {<br>            return {<br>              &#39;headers&#39;: {&#39;Authorization&#39;: &#39;&#39;&#39;Bearer $accessToken&#39;&#39;&#39;},<br>            };<br>          },<br>          inactivityTimeout: const Duration(seconds: 30),<br>          delayBetweenReconnectionAttempts: const Duration(seconds: 10),<br>          onConnectionLost: (code, reason) async {<br>            debugPrint(&#39;code $code, reason $reason, isLoggedIn $_isLoggedIn&#39;);<br>            if (code == 4400 || code == 1005) {<br>              if (_isLoggedIn.value &amp;&amp; (code == 1005 || reason == &#39;{&quot;server_error_msg&quot;:&quot;4400: Connection initialization failed: Could not verify JWT: JWTExpired&quot;}&#39;)) {<br>                // call API to get new access token here<br>              }<br>              accessToken = await secureStorage?.read(key: &#39;accessToken&#39;) ?? &#39;&#39;;<br>            }<br>            return Future.delayed(const Duration(seconds: 10));<br>          },<br>          pingMessage: {&#39;count&#39;: 0},<br>        ),<br>      );<br>      var socketLink = webSocketLink.concat(httpLink);<br>      final Link finalLink = _isLoggedIn.value<br>        ? Link.split(<br>            (request) =&gt; request.isSubscription,<br>            socketLink,<br>            httpAuthLink,<br>          )<br>        : DummyLink(); // if user is logged out from KeyCloack, then replace actual Hasura link with dummy link.<br>      _client = ValueNotifier(GraphQLClient(link: finalLink, cache: GraphQLCache()));<br>    } catch (error) {<br>      debugPrint(&#39;error in getGraphQLClient ${error.toString()}&#39;);<br>      rethrow;<br>    }<br>  }<br>}</pre><p>In the above code, we are using <strong><em>onLogin</em></strong> and <strong><em>onLogout</em></strong> methods in the login and logout APIs respectively which consist of implementation of Keycloack admin APIs. The getx variable <strong><em>_isLoggedIn</em></strong> is used to determine whether a user is authenticated. Depending on the value of <strong><em>_isLoggedIn</em></strong> variable the WebSocket client’s URL is generated.</p><p>Also, for authentication, we are using a bearer token while creating a client with a WebSocket link.</p><p><strong>WebSocketLink Setup:</strong></p><ul><li>WebSocketLink is an implementation of a WebSocket transport for GraphQL subscriptions. It establishes a WebSocket connection to the specified GraphQL server endpoint.</li><li>url: &#39;&lt;YOUR-GRAPHQL-SUBSCRIPTION-ENDPOINT&gt;&#39;: Replace &lt;YOUR-GRAPHQL-SUBSCRIPTION-ENDPOINT&gt; with the actual WebSocket endpoint provided by your GraphQL server for handling subscriptions. This URL typically starts with ws:// or wss://.</li><li>config: SocketClientConfig(...): This provides configuration options for the WebSocket connection.</li><li>autoReconnect: true: Enables automatic reconnection in case of disconnection.</li><li>delayBetweenReconnectionAttempts: Duration(seconds: 30): Sets a timeout duration for delaying the reconnection process of the WebSocket connection. This is used to wait until getting a new bearer token from the KeyCloack scenario.</li><li>inactivityTimeout: Duration(seconds: 30): Sets a timeout duration for detecting inactivity and closing the WebSocket connection if no communication occurs within this time.</li><li>onConnectionLost: After the expiration of the token, WebSocket throws an error with code 1005 or 4400 in this callback function, for that error, we call API to get a new access token from KeyCloack and again assign the new bearer token to the accessToken variable.</li></ul><p><strong>GraphQLClient Setup:</strong></p><ul><li>GraphQLClient is instantiated with the WebSocketLink as the communication link for subscriptions and a GraphQLCache for caching.</li><li>link: websocketLink: Specifies the WebSocketLink as the communication link for the GraphQL client. This ensures that subscriptions are handled over the WebSocket connection.</li><li>cache: GraphQLCache(): Initializes a cache for storing and managing the GraphQL client&#39;s local state and query results.</li></ul><pre>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br><br>class DummyLink extends Link {<br>  @override<br>  Stream&lt;Response&gt; request(Request request, [forward]) {<br>    return const Stream.empty(); // No-op link<br>  }<br>}</pre><ul><li>Wrap your app with the GraphQLProvider Inherited Widget to use GraphQL widgets in your UI files with client object from <strong><em>GraphqlAuthController</em></strong>:</li></ul><pre>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:get/get.dart&#39;;<br><br>import &#39;graphql_auth_controller.dart&#39;;<br><br>class MyApp extends StatelessWidget {<br>  MyApp({<br>    super.key,<br>  });<br><br>  final GraphqlAuthController authController = Get.put(GraphqlAuthController());<br>  <br>  @override<br>  Widget build(BuildContext context) {<br>    return GraphQLProvider(<br>      client: authController.client,<br>      child: GetMaterialApp(<br>        title: &#39;App&#39;,<br>        home: HomeScreen(),<br>      ),<br>    );<br>  }<br>}</pre><h3>Implement the subscription query</h3><p>For the implementation of subscription in our code, we are using the following subscription query.</p><pre>subscription get_notifications_count($user_id: uuid!) {<br>notifications_aggregate(where: {<br>  type: {_in: [Notification]},<br>  user_id: {_eq: $user_id},<br>  is_read: {_eq: false}<br>  }) {<br>    aggregate {<br>      count<br>    }<br>  }<br>}</pre><p>For generating the dart class for the above query we are using the build_runner and graphql_codegen packages and build.yaml file</p><pre>targets:<br>  $default:<br>    builders:<br>      graphql_codegen:<br>        options:<br>          clients:<br>            - graphql_flutter<br>          generatedFileHeader: &quot;// ignore_for_file: type=lint\n&quot;<br>          addTypenameExcludedPaths: <br>            - subscription #main step to ignore typename for subscription queries</pre><p>to generate dart code for any GraphQL queries, execute the following command:</p><pre>$ dart run build_runner build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*fCLf3NvGxwNMt_KqKED4aQ.png" /></figure><p>After running the above command, we will see the auto-generated file named get_notification_count.graphql.dart which will consist of all the classes related to the query.</p><p>Now, let’s use the subscription widget called <strong><em>Subscription$get_notifications_count$Widget</em></strong> from the generated dart file (get_notification_count.graphql.dart) as below,</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:get/get.dart&#39;;<br>import &#39;package:graphql_flutter/graphql_flutter.dart&#39;;<br><br>import &#39;../../../graphql/subscription/get_notification_count.graphql.dart&#39;;<br>import &#39;home_screen_controller.dart&#39;;<br><br>class HomeScreen extends StatelessWidget {<br>  final HomeController homeController = Get.put(HomeController());<br>  HomeScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Material(<br>      child: Obx(<br>        () {<br>          if (homeController.userId.isEmpty) {<br>            return const Center(<br>              child: CircularProgressIndicator(<br>                color: Colors.blueAccent,<br>              ),<br>            );<br>          }<br>          final Options$Subscription$get_notifications_count subscriptionOptions = Options$Subscription$get_notifications_count(<br>            fetchPolicy: FetchPolicy.networkOnly,<br>            variables: Variables$Subscription$get_notifications_count.fromJson({<br>              &#39;user_id&#39;: homeController.userId.value<br>            }),<br>          );<br>          return Subscription$get_notifications_count$Widget(<br>            options: subscriptionOptions,<br>            builder: (result) {<br>              if (result.hasException) {<br>                debugPrint(&#39;error in notification count subscription ${result.exception.toString()}&#39;);<br>                return Center(child: Text(&#39;no data found&#39;, style: Theme.of(context).textTheme.labelLarge));<br>              }<br>              if (result.isLoading) {<br>                return const Center(<br>                  child: CircularProgressIndicator(<br>                    color: Colors.blueAccent,<br>                  ),<br>                );<br>              }<br>              if (result.data!.isEmpty) {<br>                return Center(child: Text(&#39;no data found&#39;, style: Theme.of(context).textTheme.labelLarge));<br>              }<br>              homeController.setNotificationCount(result.data!);<br>              return Obx(<br>                () =&gt; Center(<br>                  child: Text(homeController.notificationCount.value,<br>                    style: Theme.of(context).textTheme.labelLarge,<br>                  ),<br>                ),<br>              );<br>            },<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>Here we are using the Obx widget of the Getx package which is nothing but a state management tool. This widget ensures that any change obs variable will be reflected in the UI seamlessly. In this example, we use <strong><em>userId</em></strong> and <strong><em>notificationCount</em></strong> as obs variables.</p><p>For the subscription query to execute we have a dependency on the <strong><em>userId</em></strong> variable. After the checking <strong><em>userId</em></strong> value, we create an option object for the subscription widget by using the <strong><em>Options$Subscription$get_notifications_count </em></strong>class from the generated dart file (get_notification_count.graphql.dart).</p><p>In the subscription widget, we are checking general conditions like <strong><em>hasException</em></strong>, <strong><em>isLoading </em></strong>and <strong><em>isEmpty</em></strong> on the query result. After getting the correct data in the result object we call the <strong><em>setNotificationCount</em></strong> function of <strong><em>homeController</em></strong> to set the count in the <strong><em>notificationCount</em></strong> variable as shown in the below controller,</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:get/get.dart&#39;;<br><br>import &#39;../../../main.dart&#39;;<br>import &#39;../../../graphql/subscription/get_notification_count.graphql.dart&#39;;<br><br>class HomeController extends GetxController{<br>  HomeController();<br>  RxString userId = &#39;&#39;.obs;<br>  RxInt notificationCount = 0.obs;<br><br>  @override<br>  void onInit() {<br>    _loadUserInitials();<br>    super.onInit();<br>  }<br><br>  @override<br>  void onReady() {<br>    debugPrint(&#39;on ready home page&#39;);<br>    super.onReady();<br>  }<br><br>  @override<br>  void dispose() {<br>    debugPrint(&#39;dispose home page&#39;);<br>    super.dispose();<br>  }<br><br>  @override<br>  void onClose() {<br>    debugPrint(&#39;onClose home page&#39;);<br>    super.onClose();<br>  }<br><br>  void _loadUserInitials() async {<br>    userId.value = await secureStorage?.read(key: &#39;userId&#39;) ?? &#39;&#39;;<br>    userId.refresh();<br>  }<br><br>  void setNotificationCount(Map&lt;String, dynamic&gt; data) {<br>    Subscription$get_notification_count notificationData = Subscription$get_notification_count.fromJson(data);<br>    notificationCount.value = notificationData.notifications_aggregate.aggregate?.count ?? 0;<br>    notificationCount.refresh();<br>  }<br>}</pre><p>The above home controller which is extended by GetxController is mainly used to get <strong><em>userId</em></strong> from secureStorage and set the <strong><em>notificationCount </em></strong>by using <strong><em>Subscription$get_notification_count</em></strong> class from the generated dart file (get_notification_count.graphql.dart) whenever the <strong><em>setNotificaitonCount</em></strong> function is called. After setting the count in the <strong><em>notificationCount</em></strong> variable the UI updates with a new count.</p><h3>Conclusion</h3><p>This guide offers a comprehensive understanding of implementing GraphQL subscriptions in Flutter with the Hasura engine and Keycloak authentication. With an emphasis on real-time data streaming through GraphQL subscriptions, developers can seamlessly integrate GraphQL into their Flutter projects. This valuable resource provides developers of all levels with the skills to optimize data retrieval, improve app efficiency, and deliver dynamic user experiences using the power of GraphQL in Flutter.</p><p>Lastly, remember to use the latest versions of the mentioned packages to avoid any issues in the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8ecbcfe039c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>