Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Iâm a Developer Evangelist at Stream, and API for Feeds and Chat, and I have the luxury of playing around with our various tools, amazing UI Kits, and new products! For many years, Stream has been the leading provider of feeds as a service, powering the feeds for over 500+ million end users. Over the last few months, the team has been hard at work on a new product offeringâââChat.
In this tutorial, Iâll walk you through how to build a simple messenger style app with React Native, Gifted Chat (React Native Chat Components by Stream are currently in development), Serverless, and of course, Chat by Stream. To add to the mix, Iâll introduce a backend Lambda function that will auto-respond with Chuck Norris jokes and facts provided by a third-party API.
For the heavy lifting, weâll be using Stream Chat JS, a JavaScript SDK that communicates directly with the Stream API.
I should also point out that Iâll be using macOS and iOS so the tutorial may be slightly off if you are using Windows or Linux.
To follow along with this post, make sure that youâve installed and/or set up the following:
Looking for the codebase? You can find the open-source code here. How about a quick demo? Iâve got that too! Have a look at the demo on Appetize.
Letâs have some fun! đ
1. Configure Chat by Stream
Head over to https://getstream.io and click on the âSign Upâ buttonâââtop right of the website. Follow the prompts from there.
Once you are redirected, head to https://getstream.io/chat/#pricing and click on the âStart Trialâ buttonâââthis will enable chat for your account on a trial basis (14 days). Once the trial is set, youâre almost there!
https://getstream.io/chat/#pricing
Head back to the dashboard and click on your application. The dashboard defaults to âFeedsâ, so please click on the âChatâ button at the top.
From here, if you scroll down, you will see the various settings for your newly chat enabled app. Make sure to keep this open in a new tabâââyou will need the Key, Secret (bottom), and App ID (top) from this page.
If you are interested in a pricing and product comparison for Stream Chat, have a look at this.
2. Setup Serverless
When you only have a couple of required endpoints, similar to this build, Serverless often makes the most sense. Spinning up servers can take quite a bit of time and can be pretty pricey. Iâm not saying that a Serverless environment is for everyone and everything, however, I am saying that if youâre building a tiny little API, a Serverless environment is definitely the way to go.
Head over to https://dashboard.serverless.com and create a new account. Follow the onboarding sequence (email verification, username selection, app creation, etc.). Once your application is created, save the tenant name (e.g. nick-chuck username = nickchuck tenant), and also save the app nameâââweâll need both of these in the next couple of steps.
3. Create a React Native App with Expo
Expo simplifies the process of building a React Native app through the use of the Expo APIs. Technically, we donât need it at all; however, if you are looking to quickly throw something together and potentially get a build out the door for iOS or Android, Expo will be the fastest way to do so. After all, you can always eject from your Expo project.
To create your app, open your terminal and head over to a directory of your choice (Iâll be in ~/Code). Once youâre all set, run the following command to scaffold the project.
$ expo init react-native-chat-chucky
Follow the prompts from the Expo CLI and choose âblankâ for the tabs vs. blank question. Once youâre finished with the questions, Expo will generate the directory and install the necessary dependencies using yarn or npm. Your terminal should look something like this:
All set! đ
4. Add Chat SDK to React Native Chat
Next, letâs go ahead and install all of the required dependencies using the command below. Iâll be using yarn for this, but if you chose npm during your initial setup, please use that to avoid mixed lock files.
$ yarn add axios md5 react-native-gifted-chat react-native-iphone-x-helper react-native-parsed-text react-router-native stream-chat
5. Add Default Message
To display the chat interface, weâre using react-native-gifted-chat, an awesome UI library specifically designed to handle chat applications. With Gifted Chat, we can set the UI aside and get up and running quickly!
To kick off an initial message, weâll need to create a new directory and a messages file. The UI is already hooked up to require this file, so itâs a matter of creating it and dropping in a custom message.
$ mkdir data && touch messages.js
Once youâve completed that step, past the following snippet into the file and save.
Good to go! đ
6. Add Routing & Screens to React Native
We have all of the necessary dependencies in place, so letâs move on and tie everything together!
Modify your App.js file to contain the following code snippet.
Create a directory called screens and create two files withinâââChat.js and Login.js.
$ mkdir screens && cd screens && touch Chat.js && touch Login.js
Once those two files are in place, weâll need to populate them! Drop the code shown below into the appropriate files.
Chat.js
Login.js
On line 22, drop in the Stream App ID from your Stream Dashboard. On line 53 you will need to add your Lambdaâs endpoint provided by AWS API Gatewayâââdonât worry, you do not have this just yet, weâll cover it in an upcoming section.
Woo! Almost there! đšâđ
7. Add Serverless Directory &Â Files
Now that you have successfully scaffolded a React Native application using Expo, move into the directory (e.g. react-native-chat-chucky).
$ cd react-native-chat-chucky
First things first, letâs go ahead and create a new directory called serverless and then move into that directory so we can install a few dependencies.
$ mkdir serverless && cd serverless
Create a new package.json file.
$ touch package.json
Then, copy the contents of the example snippet below into your package.json file.
After adding the package.json file, make sure to run yarn within the serverless directory to properly install the modules.
Once you have completed the steps above, youâll want to copy/paste the following file contents into your serverless directory.
.eslintrc.json
.prettierrc
webpack.config.js
serverless.yml
At the top of your serverless.yml file is where you will define your tenant name and app name saved from the Serverless Dashboard. In my case, Iâm using nickchuck as my tenant name and chuck-norris as my app name.
Nice work! đ
8. Setup AWS
There is a great deal of information on the web supporting how to do this. Iâm going to provide the necessary steps, but itâs definitely something I recommend you read up on!
One crucial thing to note is that Serverless requires several different AWS IAM privileges. S3, CloudFormation, API Gateway, and Lambda to name a few. There are ways to scope the IAM privileges only to meet the necessary requirements which can be found here. Iâve found that while this is the most secure approach to take, itâs certainly not the fastest. Iâll make the recommendation that if this is a personal AWS account, save yourself some time and give your account âAdministratorAccessâ privileges from IAM.
After setting up your AWS account and IAM privileges, use the aws-cli to specify your credentials in the command line (credentials can be found under IAM).
$ aws configure
The aws-cli will ask for your Access Key ID and Secret Access Key. It will also ask you a couple more (optional) questions so the AWS CLI can provision your profile correctly.
Need to install the aws-cli for the first time? Itâs super easy on macOS. Just run brew install aws-cli and Homebrew will take care of the rest for you!
Good job! đș
9. Deploy Your Serverless Build
With AWS configured and your AWS credentials securely stored on your machine, itâs time to deploy the Serverless build to Lambda! Navigate to your serverless directory within the React Native codebase and then run the following command!
If you have not installed the Serverless CLI, you can do so with npm install -g serverless.
$ sls deploy
The build will kick off, and you should start to see logging in real-time!
Run into an issue? Please drop detailed information in the comments at the end of this post and Iâll help you out!
Boom! đ„
10. Enable API Gateway to Start Serving Requests
Serverless has completed some heavy lifting for you, automating much of the build. Before Serverless was around and we only had Lambda to work with, things were definitely a bit temperamental and cumbersome at times. With a Lambda only workflow, we used to be required to zip up our codebase (node modules and all) and then upload the zip file manually to AWS. Yuck! đ«
To verify that your Lambda was provisioned along with API Gateway, login to AWS and search for APIÂ Gateway.
AWS DashboardâââAPIÂ Gateway
Click âAPI Gatewayâ, and youâll be redirected to the dashboard with a list of your APIs. I have a few under my account, so itâs likely it will show something different. Youâre ideally looking for something called prod-<YOUR_APP_NAME>. In my case, it is prod-react-native-app. Click on the correct API to view your resources.
With the top root resource selected, click on the âActionsâ dropdown and select âDeploy APIâ.
A modal will be displayed for you to specify your âstageâ. If you donât already have a âstageâ in the dropdown, create a new one and call it whatever you would like. I opt-in for the name âprodâ because when I push to Lambda, itâs generally been tested using serverless-offline and is production ready.
API GatewayâââDeploy API
Click âDeployâ and your API will be deployed to API Gateway! Now, just capture the Invoke URL and save it for the next step!
API GatewayâââStage Editor
Almost there! đ
11. Specify Init Endpoint in Chat.js
With your invocation URL saved, the init handler will be called by appending /init to the end of it. Go to Chat.js, line 53 and drop in your invocation URL from AWS API Gateway. This will handle fetching and generation of a server-side token which is required by Stream Chat.
With the proper URL in place, the code will make a POST to /init with the user information after the user has logged in (aka you!). The POST will return a serialized object with the user information as well as the user token that was generated.
Your endpoint is not currently secured by an API key. If you would like to enable an API key, it can be done on a route by route basis within APIÂ Gateway.
Bingo! đČ
12. Set the Webhook Reply URL
Similar to the step above, the URL will be your invocation URL with /reply appended to the end. In the Stream Chat Dashboard, scroll down to the âChat Eventsâ section and enable the webhook by sliding the toggle until it is green. Then drop your URL in the input and click âSaveâ.
Stream DashboardâââWebhooks
With the URL in place and the webhook activated, any chat events that are sent through the UI and off to Stream will be forwarded to your Lambda via POST. The body contains a lot of useful information, including the chat Identifier (CID), the user making the request, message body, and more.
If you look at the reply handler in serverless/handler.js, youâll notice that we only send back a chat message if the event is coming from a user other than âchuckââââthe preset user for Chuck Norris. Itâs rather simple logic and shouldnât be too confusing.
The Stream CLI also provides functionality for setting your Webhook URLâââyou can download the Stream CLI here. Please reference the documentation here.
One more step! đ¶
13. Fire Chat up Locally!
Youâve made it a long way. So far, weâve built a custom React Native Chat UI with Expo and Gifted Chat, tied to Stream, set up an AWS Lambda with Serverless, and configured a webhook on the Stream Chat Dashboard. Whoa, that is a lot.
Now itâs time to have some fun with Chuck Norris and hear all of the exciting stories about his life.
Use the command line to start the iOS simulator (from your project directory).
$ expo startâââios
OR
Drop into your root directory for React Native and run the command yarn start. Expo will open a new debugger window for you. Next, follow the steps below.
- Open Xcode
- Navigate to the Xcode menu bar until it drops down
- Locate âOpen Developer Toolsâ, then click on âSimulatorâ
The iOS Simulator will boot and hang out in the top right-hand corner of your window. Next, focus on the debugger window that Expo opened. In the bottom left, click âRun on iOS Simulatorâ.
The application should load in the iOS Simulator, and you should see the login screen!
Type your name and email, and click the âChat with Chuckâ button at the bottom. The app will fire off its request to the server and retrieve a valid user token provided by your app on Stream. From here, itâs all about having fun!
Stuck at the build step? Drop some details in the comments below and Iâd be happy to help you out!
If youâre looking to customize the app further or turn it into an APK (Android) or IPA (iOS), I recommend checking out the following links:
Thatâs a wrap! Chat by Stream provides the necessary backend infrastructure to build a chat product from scratch, leaving only the frontend up to you! Have a look at these React powered tutorials built on top of Stream Chat.
Like this tutorial? How about some claps? đđ
React Native Chat with Chuck Norris was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.