Skip to main content

3 posts tagged with "Cloudflare"

View All Tags

How I use my Raspberry Pi?

· 9 min read
Umut YILDIRIM
Fullstack Developer

Raspberry Pi, come out of the closet! It's time for you to shine! I'll show you how I give my Pi a good workout and I'll teach you how to do the same in this post. Let's get physical (with technology)!

Cloudflare Tunnel (Optional)

Cloudflare Tunnel allows you to access your Raspberry Pi without publicly available IP address. So let's SSH to our Pi and install cloudflared.

You don't need to do this! But I highly suggest using Cloudflare Tunnel this will make your Raspberry Pi available to internet so you can access your Pi via internet.

Install Required Softwares

  1. Our first task is to perform an update of the package list as well as upgrade any out-of-date packages. You can perform both of these tasks using the following command in the terminal.
sudo apt update
sudo apt upgrade
  1. Once the update completes, we must ensure we have both the “curl” and “lsb-release” packages. Install both of these packages by using the command below in the terminal.
sudo apt install curl lsb-release
  1. With all the required packages in place, we can finally grab the GPG key for the Cloudflared repository and store it on our Raspberry Pi. A GPG key is crucial to verify the packages we are installing are valid and belong to the repository.
curl -L https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-archive-keyring.gpg >/dev/null
  1. With the GPG key saved into our keyrings folder, our next step is to add the Cloudflared repository to our Raspberry Pi. You can add
echo "deb [signed-by=/usr/share/keyrings/cloudflare-archive-keyring.gpg] https://pkg.cloudflare.com/cloudflared $(lsb_release -cs) main" | sudo tee  /etc/apt/sources.list.d/cloudflared.list
  1. As we have made changes to the available repositories, we will need to perform another update of the package list cache. You can update this cache by using the following command within the terminal.
sudo apt update

Installing Cloudfared and setting up Tunnel to the Raspberry Pi

With the repository added, we can now proceed to install the Cloudflared package to our Raspberry Pi.

To install this package, you will want to run the following command.

sudo apt install cloudflared

Now that we have prepared our Raspberry Pi, we can set up the Cloudflare tunnel. Now let's go to Cloudflare Zero Trust dashboard and navigate to Access-> Tunnels then click on Create a tunnel. Name our tunnel to something meaningful. Cloudflare will create a new tunnel and will show you instructions on the page.

Cloudflared Zero Trust Tunnel Setup

Since we already installed cloudflared you need to copy the text on the right and paste it on SSH. Cloudflare dashboard will show Connectors at the bottom of setup page. Once your Raspberry Pi finish the code you pasted you will see your device there then you can continue your setup. You will see this page

Cloudflare Zero Trust Tunnel Route Setup

So let's make our ssh browser based. Follow these instructions;

  • Subdomain: ssh
  • Domain: Your choice you can get free domain via Freenom.
  • Path: Empty
  • Type: SSH
  • URL: localhost:22 And SAVE! Congratulations, you have successfully created your Cloudflare Tunnel. Now add this this tunnel to Applications and your are good to go!

Docker

Let's install Docker on our Raspberry Pi. Docker is a containerization platform that allows you to run applications in isolated containers. This is a great way to run applications on your Raspberry Pi without having to worry about dependencies and other issues that can arise when running multiple applications on the same device.

Install Required Softwares

  1. Our first task is to perform an update of the package list as well as upgrade any out-of-date packages. You can perform both of these tasks using the following command in the terminal.
sudo apt update
sudo apt upgrade
  1. With our Raspberry Pi entirely up to date, we can now go ahead and install Docker to the Raspberry Pi.

Luckily for us, Docker has made this process incredibly quick and straightforward by providing a bash script that installs everything for you.

You can download and run the official Docker setup script by running the following command.

curl -sSL https://get.docker.com | sh

This command will pipe the script directly into the command line. Typically it would be best if you didn’t do this; however, Docker is a trusted source.

Setting up the Pi user for Docker

We need to make a slight adjustment to our pi user before we can start using Docker without issues. This is to do with the way that the Linux permission system works with Docker.

  1. Once Docker has finished installing to the Pi, there are a couple more things we need to do. For another user to be able to interact with Docker, it needs to be added to the docker group. So our next step is to add our pi user to the docker group by using the command below.
sudo usermod -aG docker pi
  1. With the pi user added to the docker group, we can now log out of the Raspberry Pi and log back in again. This will ensure that the changes we have made to the pi user are applied.
logout
  1. Once you have logged back in, you can verify that the pi user has been added to the docker group by running the following command.
groups

You should see the docker group listed in the output. If you do not see the docker group listed, you will need to log out and log back in again. Once you have verified that the pi user has been added to the docker group, we can move on to the next step.

Increasing the Swap File Size

The Raspberry Pi is a great little device, but it does have one major drawback. It only has a small amount of RAM. This can be a problem when running Docker containers as they can use a lot of RAM. To get around this, we can increase the size of the swap file.

  1. Before we can increase our Raspberry Pi’s swap file, we must first temporarily stop it. The swap file cannot be in use while we increase it. To stop the operating system from using the current swap file, run the following command.
sudo dphys-swapfile swapoff
  1. With the swap file stopped, we can now increase the size of the swap file. To do this, we will need to edit the /etc/dphys-swapfile file. You can edit this file by running the following command.
sudo nano /etc/dphys-swapfile
  1. Once the file has opened, we need to change the value of the CONF_SWAPSIZE variable. This variable controls the size of the swap file. By default, this value is set to 100. We need to increase this value to 200. You can do this by changing the value of the CONF_SWAPSIZE variable to 200.
CONF_SWAPSIZE=200
  1. Once you have made the change, you can save the file by pressing CTRL+X and then Y to confirm the save. You can then exit the editor by pressing ENTER.

  2. We can now re-initialize the Raspberry Pi’s swap file by running the command below. Running this command will delete the original swap file and recreate it to fit the newly defined size.

sudo dphys-swapfile setup
  1. With the swap file re-initialized, we can now start it again by running the following command.
sudo dphys-swapfile swapon
  1. If you want all programs to be reloaded with access to the new memory pool, then the easiest way is to restart your device.
sudo reboot

Now what?

You can use Docker to run any application that you want. You can even run multiple applications at the same time. So here is a list of applications I use on my Raspberry Pi.

Bitwarden

Bitwarden is a free and open-source password manager that allows you to store all of your passwords in one secure location. This is a great way to keep all of your passwords safe and secure.

Here is a guide on how to install Bitwarden on your Raspberry Pi.

  1. Install Bitwarden image using CLI.
docker pull vaultwarden/server:latest
  1. Once Docker finishes downloaded Bitwarden RS to your Raspberry Pi, you can now continue.
sudo docker run -d --name bitwarden \
--restart=always \
-v /bw-data/:/data/ \
-p 127.0.0.1:9999:80 \
-p 127.0.0.1:3012:3012 \
vaultwarden/server:latest

Uptime Kuma

Uptime Kuma is a free and open-source uptime monitoring tool that allows you to monitor the status of your websites and services. This is a great way to keep track of the status of your websites and services.

Here is a guide on how to install Uptime Kuma on your Raspberry Pi.

  1. Install Uptime Kuma image using CLI.
docker pull louislam/uptime-kuma
  1. Create a volume for Uptime Kuma.
docker volume create uptime-kuma
  1. Start the Uptime Kuma container.
docker run -d --name uptime-kuma \
--restart=always \
-p 9998:3001 \
-v uptime-kuma:/app/data \
louislam/uptime-kuma

Netdata

Netdata is a free and open-source real-time performance monitoring tool that allows you to monitor the performance of your Raspberry Pi. This is a great way to keep track of the performance of your Raspberry Pi.

Here is a guide on how to install Netdata on your Raspberry Pi.

  1. Install Netdata image using CLI.
docker pull netdata/netdata
  1. Start the Netdata container.
docker run -d --name netdata \
--restart=always \
-p 9997:19999 \
-v netdataconfig:/etc/netdata \
-v netdatalib:/var/lib/netdata \
-v netdatacache:/var/cache/netdata \
-v /proc:/host/proc:ro \
-v /sys:/host/sys:ro \
-v /etc/os-release:/host/etc/os-release:ro \
--cap-add SYS_PTRACE \
--security-opt apparmor=unconfined \
netdata/netdata

Conclusion

Thank you for reading this guide. If you found this guide useful, please consider sharing it with your friends and family.

How we created Flatiron Open Source - Backend - Part 2

· 6 min read
Umut YILDIRIM
Fullstack Developer
Ian Gottheim
Fullstack Developer

Welcome to part 2 of our Flatiron Open Source adventure, where we will talk about our backend setup. We fully utilized Cloudflare in our project. We are going to explain this process step by step.

Step 1: Obtaining Free Domain

We are going to a obtain our free development domain by using a service called Freenom. Freenom Landing Create an account and find an available domain. When you finish obtaining your domain proceed to step 2. Freenom Domains

Step 2: Creating your Cloudflare Account

Cloudflare is a DNS(Domain Name Service). You can add your domain to Cloudflare and Cloudflare will protect you against bad actors and DOS attacks. Now let's create your account by clicking the Sign Up button in the top right of the webpage. Cloudflare After registering to Cloudflare you will be redirected to dashboard. You will need to click the Add Site button at the top of the webpage and enter your Freenom domain from step 1. Cloudflare Add Site Once you add your domain you will be given 2 nameserver addresses. You need to access your Freenom dashboard and click the Manage Domain button. Once finished loading, click on Managment Tools, and then Nameservers. Cloudflare Nameserver You need to copy your Cloudflare nameservers and paste them into the Freenom nameserver textboxes, and then click the Change Nameservers button. Once you click the update button, the process can take up to 20 minutes to complete. Once Cloudflare finishes the setup, you will recieve an email congratulating you on setting up your first domain.

Step 3: Cloudflare Pages Setup

Cloudflare Pages allows you to deploy your dynamic front-end applications. The platform is super fast, and is always up to date by deploying directly from your Git provider (this assumes you have a github account).

You can also check their documentation.

  1. Log in to the Cloudflare dashboard.
  2. Select your account in Account Home > Pages.
  3. Select Create a project > Connect to Git.

Configure your deployment

Once you have selected a Git repository, select Install & Authorize and Begin setup. You can then customize your deployment in Set Up Builds And Deployments.

Your project name will be used to generate your project’s hostname. By default, this matches your Git project name.

The production branch indicates the branch that Cloudflare Pages should use to deploy the production version of your site. For most projects, this is the main or master branch.

Cloudflare Name Project

Since we are using Vite 3 we will follow Vite 3 deployment for Cloudflare pages.

  1. Log in to the Cloudflare dashboard and select your account.
  2. Go to Pages > Create a project > Connect to git.
  3. Select your new GitHub repository.
  4. In the Set up builds and deployments, set yarn build as the Build command, and dist as the Build output directory.
  5. Select Environment variables (advanced) > + Add variable > configure a NODE_VERSION variable with a value of any version of Node greater than 14.18 – this example uses 16.

After completing configuration, select Save and Deploy,and wait for deployment to finish. After you have deployed your project, it will be available at the <YOUR_PROJECT_NAME>.pages.dev subdomain. After testing the website, you can add a custom domain to this website. This is becuase our domain is on Cloudflare, so we can easily add our domain to Cloudflare Pages. Click on Custom Domains and type your domain name. Cloudflare will automatically update your DNS record.

Step 4: Cloudflare KV Setup

For backend work, Cloudflare has a plaform called Workers KV. Workers KV is a global, low-latency, key-value data store. It stores data in a small number of centralized data centers, then caches that data in Cloudflare’s data centers after access.

KV supports exceptionally high read volumes with low latency, making it possible to build highly dynamic APIs and websites that respond as quickly as a cached static file would. There are some request limits and speed limits, that can be read about in the documentation here

Setup

Cloudflare KV Click on Workers, then KV on sidebar. Then click the Create namespace button and give your namespace name. Finally, add a demo key and value to test functionality.

Why We Used a Python Script for Backend Work

You might realize there is a python script on our projects root. We created that script based on the content provided by Flatiron School upon graduation (as discussed in part 1 of the blog). When you run this script it will scrape through the Flatiron files, and create a formatted output file with the necessary key:value information for the project's backend. After running the script, the content was exported to Cloudflare KV.

Step 5: Cloudflare Workers Setup

This is a simple worker that can be used to request data from Workers KV and send it to client side. It is very fast and can be used to serve static files.

Setup

To setup the worker install the Cloudflare CLI (command line interface), called wrangler, as a global package

yarn global add @cloudflare/wrangler

or

npm install -g @cloudflare/wrangler

Then run

wrangler login

and follow the instructions.

Usage

To use the worker you need to create a KV namespace and upload the files you want to serve. Then you need to add the namespace id to the wrangler.toml file.

kv-namespaces = [
{ binding = "your_binding_for_env", id = "your_namespace_id" }
]

Also change the account id with you account id in the wrangler.toml file.

account_id = "your_account_id"

Then you can run

wrangler publish

You can find the source code here.

We also gave a custom domain to this Worker. You can also give a costum domain to this worker like this image bellow. Cloudflare Workers Domain

Step 6: Cloudflare R2 Setup

We are using Cloudflare R2 because Product Design is a resources intensive cohort. There is more than 250MB of data, which is why we decided to use R2 instead of uploading these resources on the assets folder of our Github. We also gave our R2 a custom domain so we can access it on our website. This documentation explains how to add a custom domain on your R2.

Conclusion

Cloudflare is a popular choice for SaaS companies due to its wide range of free and inexpensive services. Its user-friendly documentation and abundance of resources make it an especially appealing option for new full stack engineers. I highly recommend considering Cloudflare for your project.

If you encounter any issues, it is always a good idea to try searching for a solution online. Google is a great place to start. If you are unable to find a solution through a Google search, you can also try visiting Cloudflare's community page for additional help and support. curl $REPLIT_DB_URL/key

Thank you for reading our blog post and don't forget to check our last part of Flatiron Open Source.

How we created Flatiron Open Source - Frontend

· 8 min read
Umut YILDIRIM
Fullstack Developer
Ian Gottheim
Fullstack Developer

Flatiron School

Flatiron School is a 15-week coding bootcamp, with courses in software engineering, data science, cybersecurity, and product design.

Upon completion of the course, students lose access to the internal class portal, called Canvas. Students are provided with html and javascript data files, containing information on the modules and courses used throughout the phases of the bootcamp.

Flatiron Open Source

The challenge we Hope, Ian set out of accomplish is how to make the data provided upon graduation user friendly for future review and preparation for interviews. This is what sparked the idea for Flatiron Open Source. The goal was to recreate the internal class portal for Flatiron graduates to use and collaborate.

This blog will run through the process to create the front end, while future blogs will discuss back end and user implementation

How we structured our front-end

assets/css

  • css setup and configuation with tailwind

components

  • This is where the site components are created for the specific site modules. Information has been passed down using params.

data

  • Used for params for routing to the correct links to the backend

views

  • This is where the components are rendered. Items from the components page are imported into views.

main

  • The main jsx file that gets rendered for the script for index.html. The views are imported into main, where react router is used to move through the different data.

bundle-server

Tailwindcss/DaisyUI

CSS styling was completed using the DaisyUI plugin for TailwindCSS. The inclusion of DaisyUI makes creating components seamless, and if needed allows for customization.

To get started, you must have the runtime environment, Node.js, installed, to use the package manager npm commands. Another option, which was used for this project, is to have yarn installed on your computer.

The documentation for tailwind can be found here

Step 1 Install the required packages

yarn add -D tailwindcss postcss autoprefixer
yarn tailwindcss init -p
yarn add daisyui
yarn add react-daisyui

Step 2 Set Up your tailwind.config.js files

Source code for Flatiron Open Source tailwind.config.js file can be found here

The most important piece of the source code is the additional plugin to require daisyUI.

Step 3 Add the Tailwind directives to your CSS

Source code for Flatiron Open Source tailwind directives can be found here.

That is all you need to do. The final piece is the read the documentation, and import DaisyUI components you would like to use to make styling seamless for your project.

Client Side Routing

In a React application, client-side routing refers to the process of navigating to different pages or views within the app by updating the URL in the browser, without triggering a full page reload. This allows for a smoother and more efficient user experience, as the app can quickly update the displayed content without having to fetch it from the server.

One popular library for implementing client-side routing in a React app is React Router. React Router provides a collection of components that can be used to declaratively define the different routes in your app and the components that should be displayed for each route.

Vite is a build tool that is well suited for building SPA (Single-Page Applications) with React, it provides a fast development experience with a simple setup, it also provides built-in support for client-side routing by using ES modules and it's live-reloading feature.

You can use Vite with React Router to handle client-side routing in your app. You'll need to install React Router;

yarn add react-router-dom

Then import react-router-dom to your main.jsx. This is our example;

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import './assets/css/index.css';

// Routes
/* Landing Pages */
import Landing from './views/Landing';
import Courses from './views/Courses';
import Course from './views/Course';

/* Error Pages */
import NotFound from './views/errors/NotFound';

ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter>
<Routes>
{/* Landing Pages */}
<Route path="/" element={<Landing />} />
<Route path="/courses/:course" element={<Courses />} />
<Route path="/course/:course/:phase" element={<Course />} />

{/* Error Pages */}
<Route path='/*' element={<NotFound />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
);

IDs and courses.js

Now you might ask, what is this;

<Route path="/course/:course/:phase" element={<Course/>}/>

We are using useParams react hook from react-router-dom to recieve data from URL. :course is course ID like product-design so we can request related data from courses.js.

The useParams react hook allows for dynamic routing, in this case used for the url slug. It also helps to dynamically render the correct data for the course page.

Why Vite 3

In most React applications, software engineers use the command below to scaffold React projects:

create-react-app <app-name>

The downsides to this command is speed. Create-React-App is a bundle based development server. It uses webpack, which bundles the application code before serving. The larger the codebase, the more time this will take.

bundle-server

Vite is a front-end Native ESM based development server with several advantages over create-react-app:

  • It takes advantage of the availability of native ES modules in the browser, and the rise of JavaScript tools written in compile-to-native-languages
  • Vite enhance start time by dividing the modules in an app into dependencies and source code
    • Dependencies: plain JavaScript that does not change during development (component libraries). Dependencies are pre-bundled using esbuild.
    • Source Code: non-plain JavaScript that needs transforming (JSX/CSS components). Source code is served over native ESM.Vite only serves source code as the browser requests the data and the data is currently being used. -Vite supports Hot Module Replacement (HMR) over native ESM. When a file is edited, VITE only needs to invalidate one chain between the edited module and the closest boundary, instead of re-constructing the entire site as a bundler native-esm

The documentation found here will help you start a project with vite.

yarn create vite
yarn create vite my-react-app --template react

Google Analytics

vite-plugin-radar is a Vite plugin that allows you to easily add Google Analytics and Google Tag Manager to your website.

To use the plugin, you'll first need to install it as a dependency:

yarn add vite-plugin-radar

Then, you need to register it in your vite.config.js file:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import ViteRadar from 'vite-plugin-radar'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
ViteRadar({
// Google Analytics tag injection
analytics: {
id: 'G-QYFSS4RFJQ',
},
gtm: {
id: 'GTM-TTWKD6W',
},
})
],
})

Here, analytics is your Google Analytics tracking code, which is used to track the user's actions and behavior on your website. gtm is your Google Tag Manager container code, which is used to manage your analytics tags.

Once this is done, the plugin will automatically add the required GA and GTM scripts to your HTML page and configure them based on the options you provided in the configuration.

Please note that The plugin is in beta state and its API might change, you might want to consult the documentation of the plugin for the most up-to-date information.

Responsive Design

Responsive design is a method of designing and building websites that adapt to the different screen sizes and devices that people use to access the web. It's important because more and more people are accessing the internet from a variety of devices, including smartphones, tablets, laptops, and desktops.

Tailwind CSS is a popular utility-first CSS framework that can be used to build responsive designs. It provides a wide variety of utility classes that can be used to apply CSS styles to HTML elements quickly and easily. These classes are designed to be highly composable, which means you can use them together in different combinations to create complex layouts and designs.

One of the ways Tailwind CSS helps with responsive design is through its use of "responsive prefixes" that can be added to utility classes. These prefixes allow you to apply different styles to an element based on the size of the screen. For example, you can use the "sm" prefix to apply a style only when the screen is at least 768 pixels wide, or the "lg" prefix to apply a style only when the screen is at least 1280 pixels wide.

Keep in mind that, as with all utility frameworks, it can be harder to maintain when trying to customize complex design, for that reason is recommended to use it in conjunction with a css-in-js lib or some custom css that complement the design. So don't forget to check out TailwindCSS's documentation for up-to-date information.