I’ve never been much of a front-end developer. Throughout my career my focus has been on the backend. I like designing systems, building data models, and choreographing event-driven workflows. It’s a satisfying set of problems that have challenged me since I graduated college.
But when I started working at Momento early in 2023, things changed. I started building more user facing demos that required web pages that looked better than the unstyled divs I was used to working with. So naturally, as any developer would, I asked ChatGPT to teach me how to build apps in Next.js. I picked up a bit of React and got the hang of front-end development over the course of a few months. Then I realized something – front-end development is just as hard as the backend!
The challenges are different, of course, and often lead to “slower than I would like” progress as I struggle through building something. But when Momento released the Web SDK, it was like someone gave me an easy button. And no, I’m not just saying that because it’s my job. It’s seriously way easier. Let me explain.
Backend capabilities without building a backend
Ok, that section header sounds like a lie. But it’s not! When you use the Momento Web SDK in your React, Angular, Vue, Astro, whatever UI framework you like, you get access to managed, serverless services without having to build them. You get access to a cache and managed WebSockets with nothing more than simple API calls.
This means you get direct access to database-like features that let you cache API calls, build user-session stores, and save files temporarily in a remote location when you use Momento cache. Many front-end frameworks allow you to do these things with session and local storage, but they’re tied to a browser. With Momento, the constraints are cut loose. You get all these abilities cross-browser sessions and even cross-machine.
Charged only for data transfer into and out of Momento with a 5GB monthly free tier, this is a no-brainer for any front-end developer.
Session data
Instead of checking and validating local storage TTLs for your user data, just save it into Momento cache and handle defaults when you get a cache miss.
const response = await cacheClient.dictionaryGetField('user-sessions', userId, 'fullName');
if(response instanceof CacheDictionaryGetField.Hit) {
return response.value();
} else { // load from API
const data = await axios.fetch(`/api/users/${userId}`);
const user = await data.json();
cacheClient.dictionarySetFields('user-sessions', userId, userData);
return user.fullName;
}
You can store an entire JSON object in a dictionary and fetch as much of or as little of the information as you want, like a GraphQL API (almost). This can be insanely powerful as you load information about a user. You can continue to add fields to this dictionary cache item and fetch details out of it from any machine, allowing other users in your system to gain access to the data in milliseconds.
If you’ve ever visited Momento’s booth at a conference, the games we run use a similar pattern. In fact, it uses the cache as the only data store, there’s no database at all. Check out the source code.
Sharing files
Have you ever needed to securely share a file with someone but didn’t know how to build a web server, setup https, and configure a storage mechanism? Me too (assuming you said yes). Well good news, even that has become only a few lines of code.
const buffer = fs.readFileSync(filePath);
await client.set('files', fileName, new Uint8Array(buffer.buffer), { ttl: 600 });
With the image set in the cache, you can create a token scoped explicitly to that one cache key, granting temporary access to it for wherever holds the token.
const scope = {
permissions: [
{
role: 'readonly',
cache: 'files',
item: {
key: fileName
}
}
]
};
const token = await authClient.generateDisposableToken(scope, ExpiresIn.minutes(10));
return token.authToken;
In this example. the file is only available for 10 minutes so you don’t have to worry about your secure data being stale or left unknowingly on a server somewhere. With automatic time to live (TTL), your files are removed with no additional work.
For a full example file sharing app, you can check out our reference application.
チャット
You can build an entire chat app using only a front-end framework and Momento! Store the users and messages in cache items and notify people when a message is sent by publishing to Momento Topics. No lengthy auth mechanisms, connection management, or databases necessary. If you want to create short-lived, session-based chats, this is the perfect solution.
When messages are sent to a chat room, you can store them in a list cache item. This type of cache item will store things chronologically, allowing you to keep a thread-safe history of all messages in the order they were sent.
const msg = JSON.stringify({ username: name, message: message });
cacheClient.listPushFront('chat', router.query.room, msg);
When people enter or leave a room, add them to a set cache item. This item type saves an unordered array of distinct items. This means if one user is having issues with network connectivity and keeps leaving and rejoining, it’s ok – the set will deduplicate them so you don’t have to.
cacheClient.setAddElement('chat', `${router.query.room}-users`, username);
After somebody has typed in their chat message and hits the “Enter” button, you can publish a message to everyone in the chat room in a single call, notifying them instantly of the new message.
const msg = { username, message, timestamp: new Date().toISOString() };
topicClient.publish('chat', router.query.room, JSON.stringify(msg));
Chat rooms come in many flavors. Check out our blog post on a full build we did in Vercel with accompanying source code.
Interactive sites
Nothing is more whimsical than loading up a webpage and seeing a mouse zoom across the screen that doesn’t belong to you. Collaborative platforms are all the rage and they can’t be done without the support of WebSockets. But WebSockets are hard to build and they require a server-side component. Not with Momento.
Using Momento Topics, you can connect front-end to front-end, backend to front-end, and even backend to backend. There’s no restrictions on what can produce and consume events. This means you can send reactions, build collaboration sessions, and gamify your apps without server-side components!
Simply publish to a topic to send a message and subscribe to register an event handler when an event rolls in. We’ve already seen how easy it is to publish a message in the chat example. Subscribing is as easy as setting up an event handler when a message is received and when an error occurs:
useEffect(() => {
async function subscribeForReactions() {
const sub = await topicClient.subscribe('reactions', name, {
onItem: (message) => { sendReaction(message.valueString()) },
onError: (err) => { console.error(err) }
});
setSubscription(sub);
}
subscribeForReactions();
return () => {
subscription?.unsubscribe();
}
}, []);
The event handler is completely up to you, meaning you can do anything you like in response to a message! For a practical example, you can check out my live reaction app where this code was pulled from.
Conclusion
There are tons of cool things that you can do in the front-end. Why spend time re-inventing the wheel and building your own caching mechanism or yet another WebSocket implementation? Instead, use a service that does it all for you and gives you access to an autoscaling, ultra-low latency web server directly from your browser (that’s secure, to boot)!
I’ve found this to not only be a significant time saver but also a huge total cost of ownership reduction as well. There’s no back-and-forth with the backend teams waiting for an API to be built. There’s no waiting for infrastructure to be stood up to try out something new. There’s no scheduled downtime. Our teams maintain significantly fewer moving parts. It’s serverless services in the front-end.
Quick mention on security. Remember, don’t pass long-lived API keys to the browser. Opt instead for tokens, short-lived, limited-scope values perfect for the browser.
Getting started with Momento is free! Sign in with your Gmail or GitHub account and get going in seconds! We’d love to see what you build! Hop on over to our Discord and say hello, the team is there ready to answer any questions and admire your projects.
Happy coding!