{"id":13466541,"url":"https://github.com/Blazored/LocalStorage","last_synced_at":"2025-03-25T21:32:26.846Z","repository":{"id":37752235,"uuid":"168198517","full_name":"Blazored/LocalStorage","owner":"Blazored","description":"A library to provide access to local storage in Blazor applications","archived":false,"fork":false,"pushed_at":"2024-10-09T01:35:08.000Z","size":9161,"stargazers_count":1300,"open_issues_count":25,"forks_count":119,"subscribers_count":24,"default_branch":"main","last_synced_at":"2025-03-21T12:00:11.324Z","etag":null,"topics":["blazor","blazor-applications","blazor-interop","blazor-server","blazor-webassembly","blazored","csharp","hacktoberfest","localstorage","nuget"],"latest_commit_sha":null,"homepage":"https://blazored.github.io/LocalStorage/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Blazored.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["chrissainty"]}},"created_at":"2019-01-29T17:38:30.000Z","updated_at":"2025-03-21T08:48:57.000Z","dependencies_parsed_at":"2024-02-10T00:31:32.649Z","dependency_job_id":"f86578fa-69c5-480b-80f7-31b317178102","html_url":"https://github.com/Blazored/LocalStorage","commit_stats":{"total_commits":170,"total_committers":38,"mean_commits":4.473684210526316,"dds":0.4529411764705882,"last_synced_commit":"e1139f9538752094f60ba29d4a4fa184a56c1fb2"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Blazored%2FLocalStorage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Blazored%2FLocalStorage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Blazored%2FLocalStorage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Blazored%2FLocalStorage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Blazored","download_url":"https://codeload.github.com/Blazored/LocalStorage/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245548514,"owners_count":20633598,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blazor","blazor-applications","blazor-interop","blazor-server","blazor-webassembly","blazored","csharp","hacktoberfest","localstorage","nuget"],"created_at":"2024-07-31T15:00:45.843Z","updated_at":"2025-03-25T21:32:26.341Z","avatar_url":"https://github.com/Blazored.png","language":"C#","funding_links":["https://github.com/sponsors/chrissainty"],"categories":["Libraries \u0026 Extensions","hacktoberfest","csharp"],"sub_categories":["Tools \u0026 Utilities"],"readme":"[![Nuget version](https://img.shields.io/nuget/v/blazored.localstorage.svg?logo=nuget)](https://www.nuget.org/packages/Blazored.LocalStorage/)\n[![Nuget downloads](https://img.shields.io/nuget/dt/Blazored.LocalStorage?logo=nuget)](https://www.nuget.org/packages/Blazored.LocalStorage/)\n![Build \u0026 Test Main](https://github.com/Blazored/LocalStorage/workflows/Build%20\u0026%20Test%20Main/badge.svg)\n\n# Blazored LocalStorage\nBlazored LocalStorage is a library that provides access to the browsers local storage APIs for Blazor applications. An additional benefit of using this library is that it will handle serializing and deserializing values when saving or retrieving them.\n\n## Breaking Changes (v3 \u003e v4)\n\n### JsonSerializerOptions\nFrom v4 onwards we use the default the `JsonSerializerOptions` for `System.Text.Json` instead of using custom ones. This will cause values saved to local storage with v3 to break things.\nTo retain the old settings use the following configuration when adding Blazored LocalStorage to the DI container:\n\n```csharp\nbuilder.Services.AddBlazoredLocalStorage(config =\u003e\n{\n    config.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;\n    config.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;\n    config.JsonSerializerOptions.IgnoreReadOnlyProperties = true;\n    config.JsonSerializerOptions.PropertyNameCaseInsensitive = true;\n    config.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;\n    config.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;\n    config.JsonSerializerOptions.WriteIndented = false;\n});\n```\n\n### SetItem[Async] method now serializes string values\nPrior to v4 we bypassed the serialization of string values as it seemed a pointless as string can be stored directly. However, this led to some edge cases where nullable strings were being saved as the string `\"null\"`. Then when retrieved, instead of being null the value was `\"null\"`. By serializing strings this issue is taken care of. \nFor those who wish to save raw string values, a new method `SetValueAsString[Async]` is available. This will save a string value without attempting to serialize it and will throw an exception if a null string is attempted to be saved.\n\n## Installing\n\nTo install the package add the following line to you csproj file replacing x.x.x with the latest version number (found at the top of this file):\n\n```\n\u003cPackageReference Include=\"Blazored.LocalStorage\" Version=\"x.x.x\" /\u003e\n```\n\nYou can also install via the .NET CLI with the following command:\n\n```\ndotnet add package Blazored.LocalStorage\n```\n\nIf you're using Visual Studio you can also install via the built in NuGet package manager.\n\n## Setup\n\nYou will need to register the local storage services with the service collection in your _Startup.cs_ file in Blazor Server.\n\n```c#\npublic void ConfigureServices(IServiceCollection services)\n{\n    services.AddBlazoredLocalStorage();\n}\n``` \n\nOr in your _Program.cs_ file in Blazor WebAssembly.\n\n```c#\npublic static async Task Main(string[] args)\n{\n    var builder = WebAssemblyHostBuilder.CreateDefault(args);\n    builder.RootComponents.Add\u003cApp\u003e(\"app\");\n\n    builder.Services.AddBlazoredLocalStorage();\n\n    await builder.Build().RunAsync();\n}\n```\n\n### Registering services as Singleton - Blazor WebAssembly **ONLY**\n99% of developers will want to register Blazored LocalStorage using the method described above. However, in some very specific scenarios \ndeveloper may have a need to register services as Singleton as apposed to Scoped. This is possible by using the following method:\n\n```csharp\nbuilder.Services.AddBlazoredLocalStorageAsSingleton();\n```\n\nThis method will not work with Blazor Server applications as Blazor's JS interop services are registered as Scoped and cannot be injected into Singletons.\n\n### Using JS Interop Streaming\nWhen using interactive components in server-side apps JS Interop calls are limited to the configured SignalR message size (default: 32KB). \nTherefore when attempting to store or retrieve an object larger than this in LocalStorage the call will fail with a SignalR exception. \n\nThe following streaming implementation can be used to remove this limit (you will still be limited by the browser).\n\nRegister the streaming local storage service \n\n```c#\npublic void ConfigureServices(IServiceCollection services)\n{\n    services.AddBlazoredLocalStorageStreaming();\n}\n``` \n\nAdd the JavaScript file to your _App.razor_\n\n```html\n \u003cscript src=\"_content/Blazored.LocalStorage/Blazored.LocalStorage.js\"\u003e\u003c/script\u003e\n```\n\n## Usage (Blazor WebAssembly)\nTo use Blazored.LocalStorage in Blazor WebAssembly, inject the `ILocalStorageService` per the example below.\n\n```c#\n@inject Blazored.LocalStorage.ILocalStorageService localStorage\n\n@code {\n\n    protected override async Task OnInitializedAsync()\n    {\n        await localStorage.SetItemAsync(\"name\", \"John Smith\");\n        var name = await localStorage.GetItemAsync\u003cstring\u003e(\"name\");\n    }\n\n}\n```\n\nWith Blazor WebAssembly you also have the option of a synchronous API, if your use case requires it. You can swap the `ILocalStorageService` for `ISyncLocalStorageService` which allows you to avoid use of `async`/`await`. For either interface, the method names are the same.\n\n```c#\n@inject Blazored.LocalStorage.ISyncLocalStorageService localStorage\n\n@code {\n\n    protected override void OnInitialized()\n    {\n        localStorage.SetItem(\"name\", \"John Smith\");\n        var name = localStorage.GetItem\u003cstring\u003e(\"name\");\n    }\n\n}\n```\n\n## Usage (Blazor Server)\n\n**NOTE:** Due to pre-rendering in Blazor Server you can't perform any JS interop until the `OnAfterRender` lifecycle method.\n\n```c#\n@inject Blazored.LocalStorage.ILocalStorageService localStorage\n\n@code {\n\n    protected override async Task OnAfterRenderAsync(bool firstRender)\n    {\n        await localStorage.SetItemAsync(\"name\", \"John Smith\");\n        var name = await localStorage.GetItemAsync\u003cstring\u003e(\"name\");\n    }\n\n}\n```\n\nThe APIs available are:\n\n- asynchronous via `ILocalStorageService`:\n  - SetItemAsync()\n  - SetItemAsStringAsync()\n  - GetItemAsync()\n  - GetItemAsStringAsync()\n  - RemoveItemAsync()\n  - ClearAsync()\n  - LengthAsync()\n  - KeyAsync()\n  - ContainKeyAsync()\n  \n- synchronous via `ISyncLocalStorageService` (Synchronous methods are **only** available in Blazor WebAssembly):\n  - SetItem()\n  - SetItemAsString()\n  - GetItem()\n  - GetItemAsString()\n  - RemoveItem()\n  - Clear()\n  - Length()\n  - Key()\n  - ContainKey()\n\n**Note:** Blazored.LocalStorage methods will handle the serialisation and de-serialisation of the data for you, the exceptions are the `SetItemAsString[Async]` and `GetItemAsString[Async]` methods which will save and return raw string values from local storage.\n\n## Configuring JSON Serializer Options\nYou can configure the options for the default serializer (System.Text.Json) when calling the `AddBlazoredLocalStorage` method to register services.\n\n```c#\npublic static async Task Main(string[] args)\n{\n    var builder = WebAssemblyHostBuilder.CreateDefault(args);\n    builder.RootComponents.Add\u003cApp\u003e(\"app\");\n\n    builder.Services.AddBlazoredLocalStorage(config =\u003e\n        config.JsonSerializerOptions.WriteIndented = true\n    );\n\n    await builder.Build().RunAsync();\n}\n```\n\n## Using a custom JSON serializer\nBy default, the library uses `System.Text.Json`. If you prefer to use a different JSON library for serialization--or if you want to add some custom logic when serializing or deserializing--you can provide your own serializer which implements the `Blazored.LocalStorage.Serialization.IJsonSerializer` interface.\n\nTo register your own serializer in place of the default one, you can do the following:\n\n```csharp\nbuilder.Services.AddBlazoredLocalStorage();\nbuilder.Services.Replace(ServiceDescriptor.Scoped\u003cIJsonSerializer, MySerializer\u003e());\n```\n\nYou can find an example of this in the Blazor Server sample project. The standard serializer has been replaced with a new serializer which uses NewtonsoftJson.\n\n## Testing with bUnit\nThe `Blazored.LocalStorage.TestExtensions` package provides test extensions for use with the [bUnit testing library](https://bunit.dev/). Using these test extensions will provide an in memory implementation which mimics local storage allowing more realistic testing of your components.\n\n### Installing\n\nTo install the package add the following line to you csproj file replacing x.x.x with the latest version number (found at the top of this file):\n\n```\n\u003cPackageReference Include=\"Blazored.LocalStorage.TestExtensions\" Version=\"x.x.x\" /\u003e\n```\n\nYou can also install via the .NET CLI with the following command:\n\n```\ndotnet add package Blazored.LocalStorage.TestExtensions\n```\n\nIf you're using Visual Studio you can also install via the built in NuGet package manager.\n\n### Usage example\n\nBelow is an example test which uses these extensions. You can find an example project which shows this code in action in the samples folder.\n\n```c#\npublic class IndexPageTests : TestContext\n{\n    [Fact]\n    public async Task SavesNameToLocalStorage()\n    {\n        // Arrange\n        const string inputName = \"John Smith\";\n        var localStorage = this.AddBlazoredLocalStorage();\n        var cut = RenderComponent\u003cBlazorWebAssembly.Pages.Index\u003e();\n\n        // Act\n        cut.Find(\"#Name\").Change(inputName);\n        cut.Find(\"#NameButton\").Click();\n            \n        // Assert\n        var name = await localStorage.GetItemAsync\u003cstring\u003e(\"name\");\n            \n        Assert.Equal(inputName, name);\n    }\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBlazored%2FLocalStorage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBlazored%2FLocalStorage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBlazored%2FLocalStorage/lists"}