Optimize Your Webserver by Installing a Single NGINX Module

In 2012, Google released version 1.0 of their PageSpeed modules for NGINX and Apache. It has gone largely unnoticed since then. The short of PageSpeed is that if you add it to your web server, you can configure it to optimize anything passing through it using techniques such as minification, format conversion, and even injecting scripts to lazy-load images. You can read more about what it does on the official site.

It sounded great in theory, but how properly install it with NGINX wasn’t obvious. While Google does publish scripts to help with the installation, it requires a non-trivial depth of knowledge to do right. After struggling with it for many hours, I wrote a guide for personal future reference.

I recently returned to those notes to entirely automate the process using GitHub Actions. The work is open-source and available on GitHub.



Installation

Run the following as root on a Debian-based machine:

sudo su
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 8028BE1819F3E4A0
echo "deb https://nginx-pagespeed.knyz.org/dist/ /" > /etc/apt/sources.list.d/nginx-pagespeed.list
echo "Package: *" > /etc/apt/preferences.d/99nginx-pagespeed
echo "Pin: origin http://nginx-pagespeed.knyz.org/" >> /etc/apt/preferences.d/99nginx-pagespeed
echo "Pin-Priority: 900" >> /etc/apt/preferences.d/99nginx-pagespeed
apt update
apt install nginx-full # If NGINX is already installed, an `apt upgrade` works too
echo "pagespeed on;" > /etc/nginx/conf.d/pagespeed.conf
echo "pagespeed FileCachePath "/var/cache/pagespeed/";" >> /etc/nginx/conf.d/pagespeed.conf
echo "pagespeed FileCacheSizeKb 102400;" >> /etc/nginx/conf.d/pagespeed.conf
echo "pagespeed FileCacheCleanIntervalMs 3600000;" >> /etc/nginx/conf.d/pagespeed.conf
echo "pagespeed FileCacheInodeLimit 500000;" >> /etc/nginx/conf.d/pagespeed.conf
echo "pagespeed RewriteLevel CoreFilters;" >> /etc/nginx/conf.d/pagespeed.conf
systemctl reload nginx

The installation process is explained more thoroughly on the GitHub page if you’re curious.

Once that is done, you will have an active NGINX + PageSpeed installation that will receive the same updates as upstream NGINX. You can learn more about individual filters that you can enable in the documentation.

This post was originally shared on my Building Better Software Slower blog


Source link

I built an analytics package

Today, I launched logmyapp-analytics an intuitive but small npm package.

With this new package you have the ability to log page_view and click. Meaning whenever someone clicks on a button on your site you can view that in your dashboard at here and see it in real-time when someone views a page or clicks a button. More to come than just clicks and page views.

Try it out today by clicking here

View the analytics and get your api key here


Source link

Launching: Open-source one-page checkout



Introducing Medusa Express⚡️



What if you could buy and sell products via a link that sends you directly to check-out?

Wanted to share a cool new open-source project that we have been building for our headless commerce engine. Medusa Express is a one-page checkout flow allowing you to purchase a product directly via a URL-link which can be smart in cases of e.g. retargeting campaigns, outbound sales, special releases, or bloggers that want to sell easily to their followers.

Medusa Express automatically creates pages for the products in your ecommerce backend each of them optimized to make the purchasing experience as frictionless as possible, by bundling the checkout flow alongside the product.

Access it in the top link!

How it works:

  1. A customer visits a link e.g. https://medusa.express/basic-tshirt

  2. The customer selects the variant of the product they wish to buy

  3. Customer completes the checkout flow and the order is completedHope you might find it relevant!


Source link

How to set up Vue with Tailwind CSS and Flowbite

Vue.js is a popular front-end library used by websites such as Behance, Nintendo, Gitlab, Font Awesome, and more that you can use to build modern web applications.

By installing Tailwind CSS and Flowbite you can build your project even faster using the utility-first approach from Tailwind and the interactive components from Flowbite.



Install Tailwind CSS with Vue.js

Follow the next steps to install Tailwind CSS and Flowbite with Vue 3 and Vite.

  1. Create a new Vite project running the following commands in your terminal:
npm init vite my-project
cd my-project
  1. Install Tailwind CSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
  1. Configure the template paths inside the tailwind.config.js file:
module.exports = 
  content: [
    "./index.html",
    "./src/**/*.vue,js,ts,jsx,tsx",
  ],
  theme: 
    extend: ,
  ,
  plugins: [],

  1. Create a new ./src/index.css file and add the Tailwind directives:
@tailwind base;
@tailwind components;
@tailwind utilities;
  1. Import the newly created CSS file inside your ./src/main.js file:
import  createApp  from 'vue'
import App from './App.vue'

// add this
import './index.css'

createApp(App).mount('#app')
  1. Install Flowbite by running the following command in your terminal:
npm install @themesberg/flowbite
  1. Require Flowbite as a plugin inside your tailwind.config.js file:
module.exports = 

    plugins: [
        require('@themesberg/flowbite/plugin')
    ]



  1. Import the Flowbite JavaScript file inside your main ./src/main.js file:
import '@themesberg/flowbite';

Now you can start the local server by running npm run dev in your terminal.



Flowbite components in Vue.js

You can start using all of the components from Flowbite in your Vue.js project as long as you’ve properly followed the instructions above and installed both Tailwind CSS and Flowbite.

The interactive elements such as the dropdowns, modals, and tooltips will work based on the settings that you apply using the data attributes.

Here’s an example of a modal component that you can use by adding inside your App.vue template file:

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3 + Vite" />

  <!-- Modal toggle -->
  <button class="block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button" data-modal-toggle="default-modal">
    Toggle modal
  </button>

  <!-- Main modal -->
  <div id="default-modal" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed right-0 left-0 top-4 z-50 justify-center items-center h-modal md:h-full md:inset-0">
      <div class="relative px-4 w-full max-w-2xl h-full md:h-auto">
          <!-- Modal content -->
          <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
              <!-- Modal header -->
              <div class="flex justify-between items-start p-5 rounded-t border-b dark:border-gray-600">
                  <h3 class="text-xl font-semibold text-gray-900 lg:text-2xl dark:text-white">
                      Terms of Service
                  </h3>
                  <button type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-toggle="default-modal">
                      <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>  
                  </button>
              </div>
              <!-- Modal body -->
              <div class="p-6 space-y-6">
                  <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
                      With less than a month to go before the European Union enacts new consumer privacy laws for its citizens, companies around the world are updating their terms of service agreements to comply.
                  </p>
                  <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
                      The European Union’s General Data Protection Regulation (G.D.P.R.) goes into effect on May 25 and is meant to ensure a common set of data rights in the European Union. It requires organizations to notify users as soon as possible of high-risk data breaches that could personally affect them.
                  </p>
              </div>
              <!-- Modal footer -->
              <div class="flex items-center p-6 space-x-2 rounded-b border-t border-gray-200 dark:border-gray-600">
                  <button data-modal-toggle="default-modal" type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">I accept</button>
                  <button data-modal-toggle="default-modal" type="button" class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:ring-gray-300 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600">Decline</button>
              </div>
          </div>
      </div>
  </div>
</template>

Source link

Build WhatsApp and SMS CRM app in 10 mins using low code



Introduction

Here’s the video tutorial for building WhatsApp and SMS CRM app. This app can let you send WhatsApp messages and SMS directly to your customers.



Prerequisites:



Source link

😳 Generating over 1,240,000 Profile Pictures at Runtime

So here’s a problem- you’re building a social media website, but you know that there will be minors (people under 18 years old) actively using the site. And on top of this, you’re too cheap to pay for image hosting for thousands of files. So what do you do?!

Cool Duck

You generate the images at runtime, or at least that’s what we did.

Red Duck

To do this, we started with a template. Our template was the body of a rubber duck and we made it a set size- 200×200.

From there, we started adding layers onto the duck: hats, beaks, wings, etc. These layers would be interchangeable by the computer.

Blue Duck

And then finally, we set up a simple endpoint that could mix and match these different layers together. If you want to see the API in action, you can check out the website here.

If you want to check out the code for the project, it’s all publicly available here. Make sure to star the repository!


Source link

How I Made an API for Duck Jokes 🦆

I’ve been working on my website for some time now, but it felt like there was something missing. I wasn’t really sure what it was, so I ignored it for a bit of time. Later that week, I was hanging out with friends and we started making puns about ducks- “wisequacks”. That’s when I had a moment of realization.

I decided to drop everything that I was doing and build a really simple API for duck jokes. Right now the API has a couple of jokes, but we need some more, so if you want to submit some, you can respond to this issue or you can just drop a pull request on this repository.

You can check out the joke API here and you can use it in any of your projects if you would like. All of the code for the project can be found in the linked repository and it is all under the MIT license if you want to use it in your own project. Cheers!

Make Sure to Drop the Repository a Star if You Like It!

Fairfield Programming Association’s Backend Server


Source link

User Experience Web Design Firms

When it comes to a great career opportunity, user experience design companies are in high demand. Whether you need help developing software or creating engaging content, there is a user experience design agency to meet your needs. Here are a few of these firms. The advantages of using these companies: All-in-one services and high-quality work. A/B testing helps you measure your success, and a dedicated team is available to guide you through the process.

Choosing a user experience design company is essential if you are looking to increase the success of your product. The right agency can help you improve your ROI and improve your overall customer service. By taking the time to learn about the process, you will get a better understanding of what the best design agency offers and how they do it. In addition, the right company can handle maintenance and research for you. The top agencies are transparent and offer a wide range of services.

UI design companies can be very effective at analyzing a company’s business goals and customer needs. They can create a great mobile app or portal that will enhance the company’s sales and brand image. These agencies are also very effective at developing user-centric websites. They understand how to make a website that is functional, enjoyable, and efficient. They also understand how to get the best out of the customers’ interactions with your products.

While many companies offer a wide range of services, their focus is mainly on marketing and innovation. While some are focused on development and implementation, others are focused on marketing and advertising. All of them focus on the needs of their clients. In addition, they work with Fortune 5s and startups to make their products appealing to the most discerning consumers. They can provide a comprehensive package of UI/UX services. The best user experience design companies also understand the value of collaboration and the importance of quality.

A great user experience design company will work with you to ensure that the website works well. In addition, they can take care of the technical part of the website. They use tools such as MockFlow and Adobe XD. These tools are very important to ensure the site is functional and usable. Ultimately, a good user experience design firm will be able to create a competitive advantage by creating a great website. Most users will spend their time on a website that functions optimally.

A good user experience design company should be able to demonstrate how the website functions with the users. They should be able to show how it makes the user feel when they visit it. The best user experience design companies will have an extensive knowledge of the basics of usability and design. This will help the client to make a good choice. The best user experience design companies will also be able to explain the importance of interaction with the website.

A good user experience design company should have a strong strategy. They should be able to provide their clients with the necessary information and a unique approach to every project. A great UX design firm should be able to communicate effectively with the client and should be able to communicate with the other company. This should be a priority. In addition, the best user experience design firms should be able to offer a high level of communication.

A successful user experience design firm should also offer a variety of services. They must have the ability to provide their clients with unique solutions. In addition to offering excellent services, user experience design companies should be able to offer their clients with a wide range of expertise. For example, a well-designed website should be easy to navigate. In addition, a good website should be easy to use. A good design firm should be able to provide the most relevant information to its customers.

In addition to creating a highly functional website, a successful user experience design company should also understand its target customers. The company should be able to offer the right products and services to their target audience. Moreover, a successful user experience is based on a good design. If a product does not meet these standards, it will not be used. There are also several other factors to consider. One of them is the size of the company.


Source link

Tried and Tested Top 10 Video Calling API



Want to integrate the secure & fastest Video calling API to your application & website? Here is the top Video calling APIs that will drive the business traffic!

To improve productivity and connectivity, A video calling feature can be integrated into any Web browser and mobile application with RTC via APIs . In this modernized world, Technology enhanced communication has already taken Place and will surely Upgrade in the Future. The use of mobile gadgets has surged at a rapid pace. The world is growing to step into the digital world where everything is accessible with just a few easy clicks through Video calling API. Behind the triumph of any company, there is a huge increase in digitalization. Now all of us prefer virtual communication not willingly but rather than giving a physical appearance. After the Covid Booster shot , Virtual seems better.
There are many prestigious organizations working on the aspect of virtual communication. The internet is flooded with so many video calling applications. These kits are developed by the software development kits that help us to communicate with the clients, corporates, and families. Because of these tools, Virtual meets becomes easy and efficient without any lags.



Here in the article, we have mentioned some effective approaches towards the Top 10 video calling API.

Why is the popularity of video calling API increasing?

The entire world has started adopting virtual activities for distant communication. If you notice, you can clearly find how students choose virtual or digital classrooms and how the healthcare industry is choosing virtual patient care assistance.
Overall, the whole market is looking to turn their business into digital hype. The video calling API has been experiencing a huge hike in Capitalism. Choosing the right method of communication depends on features of SDK. Here in the below section, we bring some of the best tools that help to leverage your business smartly with digital communication.



The best top 10 video calling API popular in the market:



1.Video SDK

The Video SDK is the driving option that makes video conferencing efficient in every possible way to explore the world of digital communication. This tool allows you to explore how the video SDK creates an impact on engagement. This tool allows the video calls to be integrated within 10 minutes along with the VideoSDK pre-built feature like whiteboards, Q&A, and polls. This video conferencing API tool supports unlimited private channels by integrating with advanced video streaming possibilities.

Video SDK provides you best API to embed video/chat in your applications. It offers Improve video engagement with reliable video conferencing running in minutes. Support of platforms like JavaScript , React JS, React native android, flutter ,iOS. It enables the opportunity to integrate real time communication SDK.



Features of Video SDK

  • Easy to integrate prebuilt live streaming SDK with 5000 participant support.
  • Real-time communication SDK with 10,000 minutes free every month.
  • It just requires 10 minutes to integrate explicit code.
  • A cost-effective tool with long term solution.
  • Unlimited channels with enhanced video quality.
  • UI support & auto-scalable parallel rooms.



2.Agora

This tool works to build a new future with the help of a real-time communication channel. The company is based on real-time communication that develops SDKs and APIs. This tool works on the engagement for the users by delivering the video call service with real-time voice and messaging, live streaming products. The company is working towards building real-time connections in the virtual world.
With Agora video conferencing API, anyone can engage by embedding the vivid voice and video application. It provides the SDKs along with the building blocks to enable the possibility of adopting the real-time engagement possibilities. The tool offers video call, voice call, interactive live streaming, recording.



Features of Agora.io APIs

  • The tool offers an intelligent network that will help to
    connect automatically in real-time analysis.
  • Select the efficient routing path with 200+ data centers.
  • Enterprise support Platforms.
  • Minimal Battery Consumption.
  • It can withstand even the sudden spike in traffic.
  • Extensive API selection with customizable UI extension.



3.ZujoNow

This company is developing its products on cutting-edge technologies. The company delivers the products to its clients based on the video conferencing tool with effective scalability. It delivers customizable SDKs to clients. The video conferencing API company is popularly dealing with the products like on-demand videos, live streaming, and real-time communication.
This is a well-crafted platform that is helping educators and other related industries. The company delivers an end-to-end solution that enables easy integration with real-time communication, on-demand video, and a content delivery network.



Features of zujo now APIs:

  • Provide inbuilt support to the healthcare, edtech, and dating business.
  • Deliver interacting experience with chatting, voice & video calling.
  • Get zero lags while connecting.
  • Low latency support with real-time video streaming encoding.



4.Daily.co

This is the real-time video and audio SDK developer platform that focuses on the clients. Best scalable video conferencing API. The platform is developing the global infrastructure solution to deliver the people throughout the world. With Daily.co, anyone can add live audio and video experience to the products along with the prebuilt user interface & creating custom layouts. This tool helps to build calls for any device with the quality video feature of 1080p HD video and screen sharing. Daily.co also supports the flexible recording options with transcriptions.



Features of Daily.co APIs:

  • It leaves the video call UI entirely up to you.
  • Automatic bandwidth and switching between group sessions.
  • Easy to use options with pre-built API.
  • Automatic tuning of video Quality.
  • Global infrastructure with HD RTMP streaming.



5.Enablex.io

This video solution tool helps build the HD-enabled videos application on different platforms. The tool supports Web applications, iOS and android platforms. This tool supports amazing APIs and SDKs that deliver one-to-one video chats along with the option of group video calls. Here one can get an extensive video chat experience for the users. Get the live interactive broadcast feature to broadcast varieties of content through the devices directly on the social media platforms like YouTube, Facebook, and other channels. The tool works on developing communication APIs that focus on providing real-time solutions.



Features of Enablex.io APIs:

  • Get advanced features like Breakout channels (rooms),
    Background blurring features.
  • One-time payment with upfront solution.
  • Customizable functionality with endless features.
  • Get end to end encryption.
  • Get customizable UI with tangible layouts.
  • Up to 100 for video meetings and 1000 for webinar mode.



6.Mirrorfly

MirrorFly is another audio and video calling API and SDK provider that offers a solution to both large and small-scale organizations. This is the versatile messaging solution working as the market’s prime product. The tool is highly customizable as compared to any other. It goes perfectly with iOS, Android, and Web Applications. With this, anyone can get the absolute chat-app solution that provides a design-enriched UI/UX. Here you can get the intuitive build with a plethora of other features. This is embedded with WebRTC that enables HD quality video interaction along with the VoIP feature that gives a dynamic voice experience.



Features of Mirrorfly APIs:

  • Real time language translation.
  • Get a 100% customizable solution.
  • Private 1 to 1 chat with offline messages.
  • Interactive Live Broadcasting with SIP calling feature.
  • Push to Talk feature with VoIP calling facility.
  • A versatile messaging solution with endless feature.



7.Twilio

The platforms develop video application tools that are fully customized and scalable. This is completely flexible for usage. This tool constructs the applications and the connectivity that builds up capitalism . It allows chats, video, and programmable chats based on real-time communication with scalability and video calling API. This is a perfect fit for enterprises from small to wide. This helps the organization to engage its users in every step of the journey. This is a flexible API for any channel which has built-in intelligence with global infrastructure support. This single platform comes with flexible APIs for any channel, global infrastructure, built-in intelligence, and many more.



Features of Twilio APIs:

  • It gives free trial credits for video groups and video P2P .
  • Cloud recording facility with workflow integration.
  • 24 hours support through the mail and chat.
  • Get endless features with an intuitive interface.



8.Cometchat

This platform is designed for providing the APIs and SDKs for the unlimited solution to a variety of industries. The platform supports a solution to various healthcare organizations, dating, the healthcare community, and social media integration. It also delivers the features like on-demand videos and live streaming and the complete authority to the users for customizing their Whitelabel. Cometchat, the video conferencing API, supports varieties of languages and solutions like voice and video calling, scalable in-app messaging, and cross-platform compatibility. This tool supports medium to large-scale organizations. The best part of the platform is It has WebRTC-enabled HD video and voice calling capabilities. They also offer the free-of-cost service that holds limited options to small-scale organizations.



Features of Cometchat APIs:

  • One-on-one text chat along with group chat facility.
  • Voice calling & video calling, conferencing tools.
  • Type and Read indicators with online Presence Indicators.
  • Drag & drop chat widgets.
  • Build a completely custom UPI & workflow.
  • Autoscaling & white label feature with message translation.



9.PubNub

This is considered one of the best in-app chats that deliver the features of real-time chat engagement. The tool offers extensive functionality, full control, and customization without the time and expense of building in-house. With this, anyone can get complete outsourcing to the clients. It delivers the features and functionalities like custom chat, in-class integrations, functionality, and Chat UI support. This is specially built for conferences, virtual conversations, meetings, and enterprise entities. Get a one-stop platform & receive top-quality integration features.



Features of PubNub APIs:

  • Get transfer the metadata pre-call facility.
  • Receive extensive plugins in one platform.
  • WebRTC signaling along with an end to end encryption.
  • Get push notifications with complete messaging broadcasting solutions.
  • Integrate, migrate & launch quickly.
  • Open-source UI kit.



10.Sinch

Sinch is another API that manages different APIs through messaging and calling facilities. Through this, anyone can receive the services like video calling, SMS verification, voice calls, and other engagement platforms. Varieties of industries receive an extensive solution from this, which includes health, telecommunications, retail, media and entertainment, and more. Through this, a lot of operators get opportunities for monetizing the wholesale and getting rid of the frauds and other activities. This video conferencing API offers an instant messaging SDK and API to the iOS, Android, and Web Applications. It gives complete freedom to the users for customization and supports SIP, VoIP, and PSTN.



Features of sinch APIs :

  • It offers high Quality video.
  • Get Personalized Messaging with Voice Calling service.
  • Live Broadcasting.
  • Personalized communication with advanced setup.
  • 600+ operators connections globally.
  • Amazing easy & intuitive interface with the endless possibilities.



Final Words

Even so, there are handful of good articles and video tutorials on internet. Most of the video conferencing API companies have effectively made effective changes in their features and will definitely upgrade in future so that they can deal with clients all across the world.
In this era, organizations need such video calling API platforms to drive their business with ease. This article will provide insight into the best video calling API platforms that support various industries with one click .


Source link

Build an Email and Social Auth for Next JS with Supabase, Tailwind CSS 3.0 and TypeScript

Next.js is a complete full-stack framework built by Vercel for creating modern web applications. With Next.js you can write the frontend code and add the backend, NodeJS code of your application to the react framework as a single project.

Not only that, but Next.js also offers exciting features such as code-splitting for performance optimization, Search Engine Optimization (SEO), pre-rendering, API routing, client-side routing, and much more.

Supabase on the other hand is an open-source Firebase alternative. It provides authentication, a Postgres database, real-time subscription, and storage for the backend of your web application. According to their Supabase website, you can create a secure and fully functional backend in less than 2 minutes.

In this article, you will learn how to do the following:

  • Install Tailwind CSS 3.0 to a Next.js app.
  • Setup and connect to Supabase.
  • Implement an e-mail and password Sign up page.
  • Implement a Sign in page.
  • Create a protected Dashboard page.
  • Add Social login authentication with GitHub



How to Install Tailwind CSS 3.0 to a Next.js app

🚀 Open your terminal.

🚀 Run npx create-next-app@latest --ts nextjs-supabase, supabase-nextjs is the app’s name, so it can be anything you want to name your app.

npx create-next-app@latest --ts nextjs-supabase

🚀 Install Tailwind CSS by running the command:

npm install -D tailwindcss postcss autoprefixer

🚀 Create tailwind.config.js and postcss.config.js configuration file by running:

npx tailwindcss init -p

🚀 Copy and paste the code below into the tailwind.config.js:

// tailwind.config.js
module.exports = 
  content: [
    "./pages/**/*.js,ts,jsx,tsx",
    "./components/**/*.js,ts,jsx,tsx",
  ],
  theme: 
    extend: ,
  ,
  plugins: [],

🚀 Inside styles/global.css file replace the content by the following code:

@tailwind base;
@tailwind components;
@tailwind utilities;

If you encounter any issues during the installation, view the full Tailwind CSS guide with Next JS.



Add Supabase to the Next.js project

To set up the Supabase backend, do the following:

🚀 Make sure you are still in your project folder and run the command.

npm install @supabase/supabase-js

🚀 Create an empty .env.local file – where the supabase credentials will be saved.

🚀 Visit https://app.supabase.io.

🚀 Create an account and a new supabase project.

🚀 On your dashboard, go to the “Settings” section.

🚀 Click “API” on the sidebar.

🚀 Find and copy your Supabase URL and SUPABASE ANON KEY.

🚀 Paste them as values into variables in the .env.local file:

NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY

Then, you need to create a file named src/utils/SupabaseClient.ts:

import  createClient  from '@supabase/supabase-js';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";

export const supabase = createClient(supabaseUrl, supabaseAnonKey);



(Optional) Disable Email confirmation

For testing purpose, make sure you disable Enable email confirmations in your Supabase Authentication settings.



Implement an email and password Sign up page



The sign up function

const  error  = await supabase.auth.signUp(
  email,
  password,
);

if (error) 
  alert(JSON.stringify(error));
 else 
  router.push('/signin');

The supabase.auth.signUp() function accepts the email and password of the user. Then, if the user is successfully created, the user is notified and redirected to the sign in page.



Sign up page in full

Create a pages/signup.tsx file and paste the following code:

import React,  useState  from 'react';

import  useRouter  from 'next/router';

import  supabase  from '../src/utils/SupabaseClient';

const SignUp = () => 
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e: React.FormEvent) => 
    e.preventDefault();

    const  error  = await supabase.auth.signUp(
      email,
      password,
    );

    if (error) 
      alert(JSON.stringify(error));
     else 
      router.push('/signin');
    
  ;

  return (
    <div className="h-screen flex items-center justify-center bg-gray-800">
      <div className="max-w-lg w-full">
        <h1 className="text-3xl font-semibold text-center text-white">
          Create new account
        </h1>

        <form className="mt-2 flex flex-col p-6" onSubmit=handleSubmit>
          <label htmlFor="email" className="text-gray-200">
            Email
          </label>
          <input
            className="py-2 px-4 rounded-md focus:outline-none focus:ring-2"
            type="email"
            id="email"
            value=email
            onChange=(e) => setEmail(e.target.value)
          />

          <label htmlFor="password" className="mt-6 text-gray-200">
            Password
          </label>
          <input
            className="py-2 px-4 rounded-md focus:outline-none focus:ring-2"
            type="password"
            id="password"
            value=password
            onChange=(e) => setPassword(e.target.value)
          />

          <button
            className="mt-10 text-lg text-white font-semibold bg-green-500 py-3 px-6 rounded-md focus:outline-none focus:ring-2"
            type="submit"
          >
            Sign up
          </button>
        </form>
      </div>
    </div>
  );
;

export default SignUp;

Here is the result of the sign up page:

Next JS Auth sign up page



Implement the Sign in page



The log in function

const  error  = await supabase.auth.signIn(
  email,
  password,
);

if (error) 
  alert(JSON.stringify(error));
 else 
  router.push('/dashboard');

The supabase.auth.signIn() function verifies if the user has an account and makes sure that only verified user has access to the dashboard page. When the user is successfully authenticated, it redirects the user to the protected dashboard page.



Sign in page in full

Paste the following code into the pages/signin.tsx file:

import React,  useState  from 'react';

import  useRouter  from 'next/router';

import  supabase  from '../src/utils/SupabaseClient';

const SignIn = () => 
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSignIn = async (e: React.FormEvent) => 
    e.preventDefault();

    const  error  = await supabase.auth.signIn(
      email,
      password,
    );

    if (error) 
      alert(JSON.stringify(error));
     else 
      router.push('/dashboard');
    
  ;

  return (
    <div className="h-screen flex items-center justify-center bg-gray-800">
      <div className="max-w-lg w-full">
        <h1 className="text-3xl font-semibold text-center text-white">
          Sign in to your account
        </h1>

        <div className="flex flex-col p-6">
          <form className="flex flex-col" onSubmit=handleSignIn>
            <label htmlFor="email" className="text-gray-200">
              Email
            </label>
            <input
              className="py-2 px-4 rounded-md focus:outline-none focus:ring-2"
              type="email"
              id="email"
              value=email
              onChange=(e) => setEmail(e.target.value)
            />

            <label htmlFor="password" className="mt-6 text-gray-200">
              Password
            </label>
            <input
              className="py-2 px-4 rounded-md focus:outline-none focus:ring-2"
              type="password"
              id="password"
              value=password
              onChange=(e) => setPassword(e.target.value)
            />

            <button
              className="mt-10 text-lg text-white font-semibold bg-green-500 py-3 px-6 rounded-md focus:outline-none focus:ring-2"
              type="submit"
            >
              Sign in with Email
            </button>
          </form>
        </div>
      </div>
    </div>
  );
;

export default SignIn;

Here is the result of the Sign in page:

Next JS Auth sign in page



Create a protected Dashboard page

Finally, the last page is the Dashboard, you can create a file name pages/dashboard.tsx:

import React,  MouseEventHandler, useEffect, useState  from 'react';

import  User  from '@supabase/supabase-js';
import  useRouter  from 'next/router';

import  supabase  from '../src/utils/SupabaseClient';

const Dashboard = () => 
  const router = useRouter();
  const [user, setUser] = useState<User ;

export default Dashboard;

Here is the result of the protected Dashboard page:

Next JS User Dashboard



Retrieve user information and sign out function

supabase.auth.user() contains the user’s details if a user is logged in, these details are available for use everywhere in your application. The function supabase.auth.signOut() enable users to logged out of the application. The useEffect function redirects the user to the login page if he/she is not signed in.



Adding GitHub Authentication

Then, in your Supabase Dashboard, you can create a GitHub OAuth application and set up the credential in your Supabase Authentication settings.

You can add this code sample in pages/signin.tsx for social auth with GitHub. But you can replace by any other third-party login system like Google, Apple, Facebook, Twitter etc.

const handleSignInWithGitHub: MouseEventHandler = async (e) => 
  e.preventDefault();

  const  error  = await supabase.auth.signIn(
    
      provider: 'github',
    ,
    
      redirectTo: 'http://localhost:3000/callback/',
    
  );

  if (error) 
    alert(JSON.stringify(error));
  
;

Inside the render function, you also need to add the GitHub social button:

<button
  className="text-lg text-white font-semibold bg-blue-500 py-3 px-6 rounded-md focus:outline-none focus:ring-2"
  onClick=handleSignInWithGitHub
>
  Sign In with GitHub
</button>

<hr className="bg-gray-600 border-0 h-px my-8" />

The social authentication validation happens asynchronously on Supabase side. We need to wait until the authentication is confirmed and redirect the user to the dashboard. So, we create a new page named pages/callback.tsx to handle this:

import  useEffect  from 'react';

import  useRouter  from 'next/router';

import  supabase  from '../src/utils/SupabaseClient';

const Callback = () => 
  const router = useRouter();

  useEffect(() => 
    const  data: authListener  = supabase.auth.onAuthStateChange(
      (event, sessionState) => 
        if (sessionState?.user) 
          router.push('/dashboard');
        
      
    );

    return () => 
      authListener?.unsubscribe();
    ;
  , []);

  return null;
;

export default Callback;



Sign in page in full with email authentication and social auth

The final code for the sign in page:

import React,  MouseEventHandler, useState  from 'react';

import  useRouter  from 'next/router';

import  supabase  from '../src/utils/SupabaseClient';

const SignIn = () => 
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSignIn = async (e: React.FormEvent) => 
    e.preventDefault();

    const  error  = await supabase.auth.signIn(
      email,
      password,
    );

    if (error) 
      alert(JSON.stringify(error));
     else 
      router.push('/dashboard');
    
  ;

  const handleSignInWithGitHub: MouseEventHandler = async (e) => 
    e.preventDefault();

    const  error  = await supabase.auth.signIn(
      
        provider: 'github',
      ,
      
        redirectTo: 'http://localhost:3000/callback/',
      
    );

    if (error) 
      alert(JSON.stringify(error));
    
  ;

  return (
    <div className="h-screen flex items-center justify-center bg-gray-800">
      <div className="max-w-lg w-full">
        <h1 className="text-3xl font-semibold text-center text-white">
          Sign in to your account
        </h1>

        <div className="flex flex-col p-6">
          <button
            className="text-lg text-white font-semibold bg-blue-500 py-3 px-6 rounded-md focus:outline-none focus:ring-2"
            onClick=handleSignInWithGitHub
          >
            Sign In with GitHub
          </button>

          <hr className="bg-gray-600 border-0 h-px my-8" />

          <form className="flex flex-col" onSubmit=handleSignIn>
            <label htmlFor="email" className="text-gray-200">
              Email
            </label>
            <input
              className="py-2 px-4 rounded-md focus:outline-none focus:ring-2"
              type="email"
              id="email"
              value=email
              onChange=(e) => setEmail(e.target.value)
            />

            <label htmlFor="password" className="mt-6 text-gray-200">
              Password
            </label>
            <input
              className="py-2 px-4 rounded-md focus:outline-none focus:ring-2"
              type="password"
              id="password"
              value=password
              onChange=(e) => setPassword(e.target.value)
            />

            <button
              className="mt-10 text-lg text-white font-semibold bg-green-500 py-3 px-6 rounded-md focus:outline-none focus:ring-2"
              type="submit"
            >
              Sign in with Email
            </button>
          </form>
        </div>
      </div>
    </div>
  );
;

export default SignIn;

The final result with Email authentication and Social login with GitHub:

Next JS Email auth social login



Conclusion

You can take the authentication process a step further by adding email verification, whereby users’ emails are verified before they are authorized to access the protected pages.

Supabase is very easy to setup and also has a well-written documentation. As a beginner, you can get your web application up and running in minutes with few installations and configurations.

Thank you for reading this far!



If want to go further and build a SaaS app

React SaaS Boilerplate is the perfect starter kit to launch your SaaS faster and better. Focus on your business, products and customers instead of losing your time to implement basic functionalities like authentication, recurring payment, landing page, user dashboard, form handling, error handling, CRUD operation, database, etc.

Next JS SaaS Boilerplate Starter


Source link