TECH PLAY

PWA

イベント

該当するコンテンツが見つかりませんでした

マガジン

該当するコンテンツが見つかりませんでした

技術ブログ

はじめに NTT西日本の中川です。 本記事ではフロントエンド(ブラウザ)だけで利用できるデータの保持方法とデータベースサービスを厳選してご紹介します。 本記事は、2025年12月時点の情報に基づきます。 対象読者 本記事が想定する対象読者は次の通りです。 駆け出しエンジニア フロントエンド縛りでデータの保持が必要な状況の人 データの保持に対して難しそうなイメージを持っている人 背景 プログラミングの勉強を始めたばかりの方や、簡単なアプリケーション開発に挑戦しようとしている方は、多くの場合、まず「どこにデータを保存するか」という課題に直面するのではないでしょうか。 最初はデータを保存しないシンプルなアプリから始めると思いますが、開発を進めるうちに 「データの保持」 というテーマは避けて通れない領域になってきます。 しかし、プログラミング学習を始めたばかりの段階では、本格的なデータベースを用意し、サーバーサイドの環境を構築するのは、個人開発の初期段階では少し敷居が高く感じられます。 「できるだけお金を使わずに」「できるだけ手軽に」 データを保持したいというのが本音ではないでしょうか。 私自身もデータをどう扱うかについて悩んだ経験があります。 サクッと作ってどんどん数をこなしたい、という当時の自分だったらという個人的なニーズが、今回の記事作成のきっかけです。 この記事が、皆さんのエンジニアライフに少しでも役立てば嬉しいです。 本記事で紹介するデータ保持アプローチの全体像 フロントエンド開発だけでデータを保持(ブラウザを閉じる/アプリのタブを閉じてもデータを保持すること)するには、大きく分けて以下の2つのアプローチがあります。 クライアントサイドで保持 : データがユーザーのブラウザ(デバイス)内に保存される サーバーサイドで保持 : データがサーバーに保存される 例:PaaS、BaaS上などのサーバーまたはストレージ 今回は、特に入門に適した以下の方法を解説します。前半のクライアントサイドの2つをメインに見ていきましょう。 カテゴリ 方法 データの保存場所 主な用途 クライアントサイドで保持 LocalStorage ユーザーのブラウザ内 (簡易データ) ユーザー設定、セッション情報の保持、簡易的なオフライン利用 IndexedDB ユーザーのブラウザ内 (構造化データ) 大量の構造化データの保持、本格的なオフラインアプリケーション (PWA) サーバーサイドで保持 Supabase/Firebase サーバー上のデータベース 複数ユーザー間の共有、認証・認可が必要な本格アプリケーション 1. LocalStorage LocalStorageは、JavaScriptの標準機能で利用できる、最も手軽なデータ保持方法の一つです。 データはユーザーのブラウザ内に保存されます。 特徴 事前準備 : JavaScriptの標準機能なのでブラウザだけですぐに利用できます 構造 : キーと値のシンプルなセット(Key-Valueストア) 保存形式 : 文字列 (String) のみ。オブジェクトや配列を保存するには JSON.stringify() で文字列化が必要 データ量 : 比較的小さい(5MB程度) 用途 : ユーザー設定(ダークモード/ライトモード)、セッション情報、簡易なToDoリストなど サンプルコード(データの保存と取得) // 【保存】キー 'username' に 'Nakagawa' という文字列を保存する localStorage . setItem ( "username" , "Nakagawa" ) ; console . log ( "データを保存しました" ) ; // 【取得】キー 'username' の値を取得する const storedUsername = localStorage . getItem ( "username" ) ; console . log ( "取得したデータ:" , storedUsername ) ; // 出力: 取得したデータ: Nakagawa // 【削除】キーを指定してデータを削除する localStorage . removeItem ( "username" ) ; console . log ( "データを削除しました" ) ; データの保存、取得、削除が3行ほどで完結します。 格納されたLocalStorageの値はブラウザの検証ツールで確認できます。 今回は、Google Chromeを利用して確認していきます。 検証ツールの起動方法 起動 Windows : Ctrl + Shift + I または F12 Mac : Command + Option + I 確認箇所 Applicationタブを選択 サイドバーのLocalStorageを選択すると自身のサイトのURLがあるので、それをクリック サンプルコードで登録した username が登録されていることを確認できる  補足(オブジェクトを保存する場合) オブジェクトを保存する場合は、値の保存/取得時に文字列変換↔︎JSON変換が必要なので要注意 const userSettings = { theme : "dark" , notifications : true } ; // ダークモードなどの設定を想定 // オブジェクトを文字列(JSON)に変換して保存 localStorage . setItem ( "settings" , JSON . stringify ( userSettings )) ; // 取得後、JSONを元のオブジェクトに戻す const storedSettingsString = localStorage . getItem ( "settings" ) ; const storedSettingsObject = JSON . parse ( storedSettingsString ) ; console . log ( "取得したオブジェクト:" , storedSettingsObject . theme ) ; Tips かつて広告トラッキングやコンバージョン計測などではよくCookieが使われていました。 数年前からAppleがSafariに ITP(Intelligent Tracking Prevention) と呼ばれるユーザーのウェブ上でのトラッキングを制限することを目的としたプライバシー保護機能を搭載したことで(Cookieの有効期間などへの規制が盛り込まれています)、LocalStorageが代替案として使われてきましたが、 最近、さらに要件が厳しくなってきています。 LocalStorageは意外と身近に使われている機能なので、興味があれば色々調べて見るととても面白いです。 2. IndexedDB IndexedDBは、LocalStorageよりも大容量で、本格的なデータベース機能をブラウザ内で提供してくれます。 非同期処理が前提で、リレーショナルデータベースに近い構造化データを扱えますので、 開発の勉強やちょっとした処理にも便利です。 特徴 構造 : オブジェクトストア(NoSQLのコレクションに相当) 保存形式 : JavaScriptのオブジェクトをそのまま保存可能 データ量 : 比較的大容量(数GBまで) 用途 : オフラインで動作するPWA (Progressive Web App) のキャッシュ、大量の構造化データ保持 サンプルコード(データの保存と取得) IndexedDBは複雑なため、今回はデータの追加 (Add) と取得 (Get) に焦点を当てたシンプルな例を紹介します。 // データベース名とバージョンを定義 const DB_NAME = 'MyTodoDB' ; const DB_VERSION = 1 ; const STORE_NAME = 'tasks' ; // データベースを開く(存在しない場合は作成) const request = indexedDB . open ( DB_NAME , DB_VERSION ) ; let db ; // データベースのバージョンが変わった時(初回作成時も含む)に実行される request . onupgradeneeded = ( event ) => { db = event . target . result ; // オブジェクトストアを作成(ここでは 'id' をキーとする) db . createObjectStore ( STORE_NAME , { keyPath : 'id' , autoIncrement : true }) ; } ; // 接続成功時 request . onsuccess = ( event ) => { db = event . target . result ; console . log ( 'IndexedDB接続成功' ) ; // サンプルデータの追加と取得を実行 addTask ({ text : '記事を完成させる' , priority : 'High' }) ; getAllTasks () ; } ; request . onerror = ( event ) => { console . error ( 'IndexedDBエラー:' , event . target . error ) ; } ; // 【保存】データの追加関数 function addTask ( task ) { // トランザクションを開始し、読み書きを許可 const transaction = db . transaction ([ STORE_NAME ] , 'readwrite' ) ; const store = transaction . objectStore ( STORE_NAME ) ; // オブジェクトをそのまま追加 const addRequest = store . add ( task ) ; addRequest . onsuccess = () => { console . log ( 'タスクが正常に追加されました:' , task ) ; } ; addRequest . onerror = ( e ) => { console . error ( 'タスク追加エラー:' , e . target . error ) ; } ; } // 【取得】全データの取得関数 function getAllTasks () { const transaction = db . transaction ([ STORE_NAME ] , 'readonly' ) ; const store = transaction . objectStore ( STORE_NAME ) ; const getRequest = store . getAll () ; getRequest . onsuccess = () => { console . log ( '全タスク:' , getRequest . result ) ; } ; } 格納された値はLocalStorage同様にブラウザの検証ツールで確認できます。 こちらも、Google Chromeを利用して確認していきます。 検証ツールの起動方法 起動 Windows : Ctrl + Shift + I または F12 Mac : Command + Option + I 確認箇所 Applicationタブを選択 サイドバーのIndexedDBを選択すると先ほど作成した「MyTodoDB」があるので、それをクリック tasksテーブルをクリック サンプルコードで登録した MyTodoDB と tasks が登録されていることを確認できる 実行方法の補足 ここまで紹介したブラウザで動く LocalStorage と IndexedDB は、試すだけなら実はわざわざファイルを作成する必要はありません。 結果を確認するために使っている検証ツールの「 Console 」というタブに、今回紹介しているコードをそのまま貼り付けるだけで動きます。 LocalStorageの章で紹介した内容をConsoleにコピペして実行 3. サーバーサイドにおけるデータ保持の紹介 最後に、クライアントサイドの制約(データ量の制限、複数ユーザー間での共有ができない)を超えて、本格的なアプリケーション開発に進むためのアプローチを簡単に紹介します。 BaaS (Backend as a Service) は、サーバー側の機能(データベース、認証、ストレージなど)を、APIを通じてフロントエンドから手軽に利用できるように提供するサービスです。サーバーサイドの構築作業を行わずに、高度なデータ保持を実現できます。 Supabase と Firebase SupabaseはPostgreSQLベースのリレーショナルなデータベース、FirebaseはNoSQLのリアルタイムデータベースを提供しています。どちらも無料枠があり、駆け出しのエンジニアが本格的なWebサービスを開発する際のデータ保持に適しています。 用途 : 複数ユーザー間のデータ共有、ユーザー認証・認可、リアルタイム通信が必要なチャットアプリなど。 特徴 : フロントエンドのコードから、サービスが提供する専用のライブラリ(SDK)を使って、クラウド上のデータベースに直接データの読み書きができます。 これらのサービスは、さらに次のステップに進むための強力な武器になります。 このブログでも機会があれば紹介したいなと思います。 一層本格的なアプリケーションに挑戦する際には、ぜひ調べてみてください。 まとめ 本記事では、プログラミング初心者やフロントエンド開発を主軸とする方が、手軽かつ安価にデータを保持するための主要なアプローチを解説しました。 この記事を通じて、データの保持は決して難しいものではなく、実は手軽に開発のニーズに合わせて適切なツールを選べることが伝えられていたら嬉しいです。まずはLocalStorageやIndexedDBで実際に手を動かし、開発を加速させていきましょう!💪 執筆者 中川 拓哉(NTT西日本 デジタル革新本部 デジタル改革推進部所属) NTT西日本の法人向けの顧客ポータルサイトを開発・運営しています。 TypeScript, Vue.js, GraphQL, Laravelが好きです。 参考文献 IndexedDB の使用 - Web API | MDN ウェブストレージ API - Web API | MDN 商標 「Supabase」は、Supabase Inc.(米国デラウェア州法人)の商標もしくは商標登録です 「Google Chrome」「Firebase」は、Google LLCまたはその関連会社の商標もしくは登録商標です
Introduction Hi, we're Yao, Bahng, and Lai from the Global Development Division. We're mobile app engineers, usually developing Global KINTO App . A few months ago, we investigated Kotlin Mltiplatform Mobile (KMM) as a preliminary activity for the future of Global KINTO App. See our previous article on this. The results of our previous investigation indicate that KMM is an excellent solution for rapid product development. Now that KMM has been revealed as a new approach compatible with Compose UI, we decided to investigate it further. Based on that investigation, this article discusses app development using Kotlin Multiplatform Mobile (KMM) and Compose Multiplatform. Before getting into the main topic, let's first clarify three points: What is KMP? What is KMM? What is the relationship between KMP and KMM? The answers are as follows: KMP: Kotlin Multiplatform, referring to the technology used to develop applications across multiple platforms using Kotlin, along with its entire ecosystem. KMM: Kotlin Multiplatform for Mobile. One of the primary use cases for KMP is code sharing between mobile platforms. In addition to KMP, several technologies specifically for mobile app development are collectively referred to as KMM. The graph below illustrates the relationship between KMP and KMM. Reference: -- JetBrains "Kotlin brand assets | Kotlin. (n.d.-c). Kotlin Help." , "Get started with Kotlin Multiplatform for mobile | Kotlin. (n.d.). Kotlin Help." Accessed June 1, 2023 Cross-Platform You may wonder about the advantages of cross-platform development, particularly when considering Kotlin Multiplatform Mobile (KMM) as cross-platform solutions. Here are the benefits: Cost-effective: Cross-platform development allows the use of a single codebase across multiple platforms, eliminating the need for separate platform development teams and reducing the cost of app development. Faster deployment: By leveraging a single codebase, developers can create and launch applications on multiple platforms simultaneously, significantly reducing development time and accelerating time to release. Simplified maintenance and updates: By using a single codebase, apps can be easily maintained and updated, allowing changes to be made once and propagated across all platforms. This streamlines the maintenance process and ensures that all users have access to the latest features. Consistent user experience: By using cross-platform development tools and frameworks, a consistent look and feel can be maintained across different platforms, providing a unified user experience. This can lead to improved user satisfaction and user retention. Shared resources and skills: Developers familiar with cross-platform tools and languages can create apps for multiple platforms. This allows for more efficient use of resources and maximizes the return on investment in developer skills and training. History of Cross-Platform Development Tools for Mobile In 2009, PhoneGap was created and later renamed Apache Cordova. In 2011, Xamarin was created by Mono and later acquired by Microsoft. In 2015, React Native was created by Facebook (Meta). In the mid-2010s, designer Frances Berriman and Google Chrome engineer Alex Russell coined the term "progressive web app (PWA)," and Google made several efforts to popularize it. In 2017, Flutter was created by Google. In 2021, KMM was created by JetBrains. This means that KMM is currently the most recent cross-platform solution available. Logo source: -- Apache "Artwork - Apache Cordova. (n.d.)." Accessed June 1, 2023 -- Microsoft "Conceptdev. (n.d.). Xamarin documentation - Xamarin. Microsoft Learn" Accessed June 1, 2023 -- Meta "Introduction · React native." Accessed June 1, 2023 -- Google "Progressive web apps. (n.d.). web.dev." Accessed June 1, 2023 -- Google "Flutter documentation. (n.d.)." Accessed June 1, 2023 -- JetBrains "Kotlin Multiplatform for Cross-Platform development" Accessed June 1, 2023 Why is KMM Different? Shared business logic: KMM reduces code duplication and maintains consistency between Android and iOS by allowing code related to business logic, networking, and data storage to be shared across platforms. True native UI: KMM allows the use of platform-specific tools and languages (e.g. XML for Android and SwiftUI or UIKit for iOS) for UI development, resulting in a more native look and feel compared to other cross-platform solutions. Performance: Kotlin code is compiled into native binaries for each platform, resulting in high-performance applications that are comparable to native development. Seamless integration: KMM can be integrated into existing projects, developers can adopt it incrementally and migrate sharing logic to Kotlin without having to completely rewrite their apps. Interoperability with native libraries: KMM seamlessly interoperates with both Android and iOS native libraries, facilitating the use of existing libraries and frameworks. Benefits of the Kotlin language: Kotlin is a modern and concise language that provides similar functionality to existing alternatives while reducing redundant code, with tool support from JetBrains. The above points are explained in detail below. (1) Shared Business Logic KMM is used when implementing the data, business, and presentation layers in new projects. Flexibility: KMM allows developers to determine the scope of code they want to share, offering a flexible implement balanced with platform-specific code as needed. Consistency assurance: While differences in UI can be easily detected in QA testing, inconsistencies between Android and iOS are difficult to detect in logic. By using KMM, the same code can be used, thus ensuring consistency. (2) Truly Native UI KMM supports native UI, uses native UI components, and follows platform-specific design patterns. Android: xml, Jetpack Compose, etc. iOS: UIKit, SwiftUI, etc. UI performance: KMM uses native UI components, and since the Kotlin code is compiled into native binaries for each platform, its performance is generally comparable to native apps. Easy platform updates: KMM makes it easy for developers to update new platform features and designs. Because it uses the native UI framework for each platform. (3) Performance No JavaScript bridge is required; no reliance on third-party libraries. Uses the system's default rendering engine, reducing resource consumption compared to other cross-platform solutions. Native code compilation: KMM compiles Kotlin code into native binaries for each platform. This native code compilation enhances app efficiency and overall performance. Android: Standard Kotlin/JVM iOS: Kotlin/Native Compiler (Objective-C) (4) Seamless Integration No need to bridge native modules or rewrite existing code. Phased adoption: KMM can be gradually introduced into existing native Android and iOS projects. This allows teams to share business logic, network, and data storage code across platforms in phases, reducing the risks associated with a complete technology switch. Multiple approaches to using KMM modules in iOS CocoaPods Gradle plugin and git submodules Framework Swift Package Manager (SPM): Starting with Kotlin 1.5.30, KMM modules are available in iOS projects using the Swift Package Manager. (5) Interoperability with Native Libraries Access to native APIs and libraries: KMM provides direct access to native APIs and libraries, facilitating easy integration with platform-specific functions and hardware components such as sensors and Bluetooth. Seamless integration with platform-specific code: KMM allows for writing platform-specific code as needed, which is useful when dealing with complex native libraries or accessing features not available through shared Kotlin code. Kotlin/Native: KMM uses Kotlin/Native for iOS. This allows seamless interoperability with Objective-C and Swift code. This means that existing iOS libraries and frameworks can be used without additional bridging or wrapping code. (6) Kotlin Language Benefits Language features: Modern, static typing, null safety, extension functions, data classes, SmartCast, interoperability with Java Tools and support: Kotlin provides exceptional support and first-class integration in Android Studio and IntelliJ IDEA. Industry adoption: Kotlin has seen rapid adoption since becoming the official programming language for Android development. Many backend developers also use Kotlin. What Kind of People are Using KMM? In fact, several companies have adopted Kotlin Multiplatform Mobile (KMM) for mobile app development. Here are some notable examples: Netflix: Netflix uses KMM in some of its internal tools to share code between Android and iOS apps. VMware: VMware uses KMM for cross-platform development of Workspace ONE Intelligent Hub app (employee management tool for Android and iOS). Yandex: Yandex, a Russian multinational technology company, has adopted KMM in several of its mobile apps, including Yandex Maps and Yandex Disk. Quizlet: Quizlet, an online learning platform, uses KMM to share code between Android and iOS apps, improving development efficiency. These companies represent diverse industries, and their adoption of KMM demonstrates the flexibility and usefulness of technology in different contexts. As KMM becomes more popular, it's likely that even more companies will adopt KMM to meet their cross-platform mobile development needs. Reference: -- JetBrains "Case studies. (n.d.). Kotlin Multiplatform." Accessed June 1, 2023 How to Easily Create a KMM Project Given these benefits, would you like to create a KMM project and give it a try? The following is a guide on how to do this. Download the latest Android Studio. In Android Studio, select File > New > New Project. Select Kotlin Multiplatform App in the list of project templates, and click Next. Specify the Name of the new project and click Next. In the iOS framework distribution, select the Regular framework. Keep the default names for Applications and Shared folders. Click Finish. -- JetBrains "Create your first cross-platform app | Kotlin. (n.d.). Kotlin Help." Accessed June 1, 2023 Mobile App Architecture Using KMM The following graph is an example of one of common KMM patterns. This architecture takes full advantage of KMM's characteristic code sharing. Data persistence, including cache, database, network, use cases, and view model are all implemented in KMM. For UI, both Android and iOS use native UI components. Support is provided for both older frameworks such as XML and UIKit, and newer frameworks such as Jetpack Compose and SwiftUI. This architecture allows business logic modules written in Kotlin to be imported into iOS as SDKs. This allows iOS developers to focus on UI development for efficient development. Here's some iOS code for a simple screen with an FAQ list. Except for the common UI Utility Class, this is all that needs to be implemented. #FaqView.swift struct FaqView: View { private let viewModel = FaqViewModel() @State var state: FaqContractState init() { state = viewModel.createInitialState() } var body: some View { NavigationView { listView() } .onAppear { viewModel.uiState.collect(collector: Collector<FaqContractState> { self.state = $0 } ) { possibleError in print("finished with possible error") } } } private func listView() -> AnyView { manageResourceState( resourceState: state.uiState, successView: { data in guard let list = data as? [Faq] else { return AnyView(Text("error")) } return AnyView( List { ForEach(list, id: \.self) { item in Text(item.description) } } ) }, onTryAgain: { viewModel.setEvent(event: FaqContractEvent.Retry()) }, onCheckAgain: { viewModel.setEvent(event: FaqContractEvent.Retry()) } ) } } That's not all about KMM. KMM has even more potential! Architecture That Shares UI Code In addition to business logic code, KMM can also share UI code using Compose Multiplatform. As we discussed earlier, Kotlin Multiplatform Mobile (KMM) is primarily used for implementing shared business logic, but it also supports shared UI development. Compose Multiplatform is a declarative framework for sharing UI across multiple platforms using Kotlin. Based on Jetpack Compose, it was developed by JetBrains and open source contributors. Combining KMM with Compose Multiplatform allows for the building of both logic code and UI using the Kotlin language. Reference: -- JetBrains "Kotlin brand assets | Kotlin. (n.d.-c). Kotlin Help." , "Compose multiplatform UI framework | JetBrains. (n.d.). JetBrains: Developer Tools for Professionals and Teams." Accessed June 1, 2023 Comparison of Different Patterns of KMM Architecture Assuming a mobile project is being developed, the estimated workloads for each client are as follows: UI: 2 people, Presentation: 1 person, Business/Domain: 1 person, Data/Core: 1 person The workloads saved from this point is based on the percentage of code written by KMM. Pattern A B C D UI 2*2 2*2 2*2 2 Presentation 1*2 1*2 1 1 Business/Domain 1*2 1 1 1 Data/Core 1 1 1 1 Total 9 8 7 5 workload cost -10% -20% -30% -50% KMM can reduce workloads by up to 50%. The biggest advantage of KMM compared to other cross-platform solutions is its flexibility in code sharing. How much code to share with KMM is entirely up to us. Other cross-platform solutions do not offer this level of flexibility. Summary Cons of KMM Of course, every tool has its drawbacks. KMM is no exception. Limited platform support: Kotlin Multiplatform Mobile can target multiple platforms, but not all platforms are supported. For example, it does not currently support web or desktop applications. Learning cost: If you are not familiar with Kotlin, there is a learning cost to effectively use it for multi-platform development. Framework compatibility: Kotlin Multiplatform Mobile can be used with various frameworks, but is not compatible with all of them. This limits your options and may require you to work within certain constraints. Maintenance overhead: Maintaining a multiplatform codebase can be more complex than maintaining a separate codebase for each platform. This added complexity can lead to increased overhead in testing, debugging, and maintenance. Tool limitations: Some tools and libraries may not be compatible with Kotlin Multiplatform Mobile, making development more complicated or requiring the search for alternative solutions. Applications As mentioned above, integrating KMM's architecture into a project can be considered in various situations, each with it’s pros and cons. Pattern A B C D General existing project ✓ ✓ ✓ ? Simple existing project ✓ ✓ ✓ ✓ Complex existing project ✓ ✓ ✓ ✗ New project ✓ ✓ ✓ ✓ Prototype ✓ ✓ ✓ ✓ With the technical benefits covered, let's get back to the actual development process. Like most mobile development teams, ours is small. Given our limited engineering resources, when faced with a significant change, such as upgrading from version 1.0 to 2.0, we need to collaborate with other divisions and both onsite and offshore outsourcing teams to ensure a quick release. However, there are several problems in this process: Seamless collaboration between different teams is challenging. With more developers and different teams in different offices, communication costs increase. It becomes difficult to maintain consistency across different teams. Working with external teams makes it difficult to manage the security of sensitive information. KMM can address almost all of these problems by developing core modules, defining protocols, and adopting a separate approach for UI and logic development: Allows each team to focus on their part. Can greatly facilitate collaboration. Reduces the time and cost required for communication. By having the core modules developed by the KMM team on a consistent basis, most inconsistencies are eliminated in advance. Although KMM supports a single codebase, the separation of the UI and logic layers allows for the use of multiple repositories. The core modules are developed by the KMM team and the SDK is provided to external teams. This eliminates the need for the source code to be disclosed to external teams and reduces the risk of leaking confidential information. This is difficult to achieve with other cross-platform technology solutions. In conclusion, it can be said that KMM brings significant benefits not only in terms of technical advantages but also in fostering cooperation across divisions and companies. Conclusion Given the importance of KMM in new projects and its potential for significant workload savings, we have already integrated KMM into new projects for the next major release. We will continue to monitor new technologies and tools related to KMM and seek opportunities to further enhance efficiency.

動画

該当するコンテンツが見つかりませんでした

書籍

該当するコンテンツが見つかりませんでした