Blog

How to Send Emails in Node.js Using SendGrid

Sending emails is a fundamental feature in many web applications, enabling functionalities such as user onboarding, password resets, notifications, and more. In this post, we’ll explore how to send emails from a Node.js application using SendGrid, a reliable and scalable email delivery service.

When Does a Node.js App Need to Send Emails?

Emails play a crucial role in various aspects of web applications. Here are some common scenarios where your Node.js application might need to send emails:

  • User Registration: Sending welcome emails or account verification links.
  • Password Resets: Allowing users to reset their passwords securely.
  • Order Confirmations: Notifying users about their purchases.
  • Newsletters: Keeping users informed about updates and promotions.
  • System Alerts: Informing administrators about system events or errors.

Implementing email functionality enhances user experience and keeps users engaged with your application.

Why Use SendGrid?

SendGrid is a cloud-based email delivery service that offers a robust API for sending emails. Here are some advantages of using SendGrid:

  • Scalability: Capable of handling large volumes of emails efficiently.
  • Deliverability: High deliverability rates ensure your emails reach the inbox.
  • Analytics: Provides insights into email performance, such as open and click rates.
  • Templates: Supports dynamic templates for personalized emails.
  • Security: Offers features like two-factor authentication and API key permissions. 

With SendGrid, you can focus on building your application while relying on a trusted service for email delivery.

Setting Up SendGrid in a Node.js Application

Let’s walk through the steps to integrate SendGrid into your Node.js application.

1. Create a SendGrid Account and API Key

  • Sign up for a free SendGrid account at sendgrid.com.
  • After verifying your email, navigate to Settings > API Keys.
  • Click on Create API Key, provide a name, select Full Access, and create the key.
  • Copy the generated API key and store it securely.

2. Install SendGrid’s Node.js Library

In your Node.js project directory, install the @sendgrid/mail package:

npm install @sendgrid/mail

3. Configure SendGrid in Your Application

Create a file named sendEmail.js and add the following code:

const sgMail = require('@sendgrid/mail');
// Set your SendGrid API key
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// Define the email message
const msg = {
  to: 'recipient@example.com', // Replace with your recipient's email
  from: 'sender@example.com',  // Replace with your verified sender email
  subject: 'Hello from SendGrid',
  text: 'This is a plain text version of the email content.',
  html: '<strong>This is the HTML version of the email content.</strong>',
};
// Send the email
sgMail
  .send(msg)
  .then(() => {
    console.log('Email sent successfully.');
  })
  .catch((error) => {
    console.error('Error sending email:', error);
  });

Ensure you have set the SENDGRID_API_KEY environment variable with your API key.

4. Run the Email Script

Execute the script using Node.js:

node sendEmail.js

If configured correctly, you should see a confirmation message, and the email will be delivered to the specified recipient.

Additional Features

SendGrid offers additional functionalities to enhance your email capabilities:

  • Attachments: Include files in your emails by adding an attachments array to the message object.
  • Dynamic Templates: Create and manage email templates within SendGrid for consistent branding and personalization.
  • Batch Sending: Send emails to multiple recipients efficiently.
  • Event Webhooks: Receive real-time notifications about email events like opens, clicks, and bounces.

Explore SendGrid’s official documentation for more details on these features.

Alternatives to SendGrid

There are other options for sending emails in a Node.js application. You do not have to use SendGrid. For example, you can use Mailgun. Mailgun is a transactional email API service designed for developers. It offers a robust API to send, receive, and track emails effortlessly. Another option is to use Nodemailer. Nodemailer is a module for Node.js applications that allows easy email sending via SMTP. It’s ideal for sending emails through services like Gmail, Outlook, or any custom SMTP server.

Let me know in the comments section, or contact me, if you want to see examples of how to use Mailgun or Nodemailer.

Conclusion

Integrating SendGrid into your Node.js application streamlines the process of sending emails, allowing you to focus on building features rather than managing email infrastructure. With its scalability, reliability, and rich feature set, SendGrid is a valuable tool for any developer looking to implement email functionality.

Start sending emails in your Node.js projects today to enhance communication with your users.

Using JSON Web Tokens (JWT) for Stateless Authentication in Node.js

JSON Web Tokens (JWT) provide a simple, scalable way to authenticate users in your APIs without storing session state on the server. A JSON Web Token is a compact string that represents signed JSON data. It consists of three parts, each Base64-URL encoded and separated by dots:

<Header>.<Payload>.<Signature>

  • Header – Specifies the signing algorithm and token type.
  • Payload – Contains claims (e.g. user ID, roles, issued-at/expiration timestamps).
  • Signature – Ensures the token hasn’t been tampered with.

Because the signature is derived from the header + payload and a secret (or private key), you can verify both the integrity and authenticity of the token.

How JWTs Work

  1. Client logs in with credentials (e.g. email/password).
  2. Server validates the credentials and issues a JWT (jwt.sign).
  3. Client stores the token (e.g. in memory, localStorage, or a secure cookie).
  4. Subsequent requests include the token in the Authorization header (Bearer <token>).
  5. Server verifies the token (jwt.verify) on each request—no session lookup required.

Install & Configure

In most of my Node.js applications that use JWT for authentication, I use a popular library called jsonwebtoken. This can be installed with the below command.

npm install jsonwebtoken

Use the --save flag with the above command to add it to your project’s package.json file.

Generating a Token

const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET || 'replace-with-strong-secret';
// Create a payload with standard and custom claims
const payload = {
  sub: user.id,       // subject (user identifier)
  name: user.name,    // custom claim
  role: user.role     // custom claim
};
// Sign a token that expires in 1 hour
const token = jwt.sign(payload, SECRET, { expiresIn: '1h' });
console.log('Generated JWT:', token);

The above code shows how to create a token and sign it. You can add whatever data you need to authorize the user in the payload section of the token.

Verifying a Token

const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;
try {
  const decoded = jwt.verify(token, SECRET);
  console.log('Decoded payload:', decoded);
} catch (err) {
  // TokenExpiredError or JsonWebTokenError
  console.error('JWT verification failed:', err.message);
}

In the above code, you can see how to validate a token, and then retrieve/decode the information that you stored in its payload.

Protecting Routes with Express Middleware

// auth.js
const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader?.split(' ')[1]; // Bearer <token>
  if (!token) return res.sendStatus(401); // Unauthorized
  jwt.verify(token, SECRET, (err, user) => {
    if (err) return res.sendStatus(403);   // Forbidden
    req.user = user;                       // attach payload to req
    next();
  });
}
module.exports = authenticateToken;

The above code shows how to create a generic function that you can use to authenticate a token.

// server.js
const express = require('express');
const jwt = require('jsonwebtoken');
const authenticateToken = require('./auth');
const app = express();
app.use(express.json());
// Public login route
app.post('/login', (req, res) => {
  // TODO: validate user credentials…
  const token = jwt.sign({ sub: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
  res.json({ token });
});
// Protected profile route
app.get('/profile', authenticateToken, (req, res) => {
  res.json({ message: `Welcome back, ${req.user.name}!` });
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));

The above code shows how to add a middleware function to a route. If the function validates the token, the route can be executed. Otherwise, the user gets a 403 error.

Best Practices

Here are some best practices for using JSON Web Tokens (JWT) for authentication in a Node.js application. First of all, use short expiration values. In my example above, my token expires in 1 hour, but you can specify a value in minutes (15 minutes, for example). If you need your users to have longer sessions, a recommended practice is to implement refresh tokens.

Second, and this should go without saying, but never save sensitive information in the payload of the token. Data like passwords or personal information. And, always use HTTPS in your applications (whether you use JWT or not).

And, finally, the SECRET for signing and verifying tokens should be saved in a secure.

Conclusion

With JWTs and the jsonwebtoken package, you can build a stateless, scalable authentication layer for your Node.js applications. This approach reduces server memory overhead and simplifies horizontal scaling—perfect for APIs, SPAs, and mobile backends.

Ready to take it further? Consider adding refresh-token rotation, role-based access control, or integrating with OAuth2 providers.

Happy coding!

How to fix quota restrictions, cannot run builds in this region

If you have an application that you want to deploy to Google Cloud Run, but you’re getting the error “(gcloud.run.deploy) FAILED_PRECONDITION: failed precondition: due to quota restrictions, cannot run builds in this region. Please contact support“, then this blog post is for you.

I have a Node.js application that has been running smoothly for a couple of years now. The application is hosted on Google Cloud Platform using Cloud Run. However, recently, when I was trying to deploy an update to this application by running the below command:

gcloud run deploy ...

I started getting this error:

(gcloud.run.deploy) FAILED_PRECONDITION: failed precondition: due to quota restrictions, cannot run builds in this region. Please contact support

Looking at the quotas on Google Cloud Console did not reveal anything to me. I was not exceeding any quotas, and everything related to billing was in order.

The Solution

After digging through the Google Cloud forums, I came across a post that suggested that the issue was caused by a recent update to the gcloud CLI. If you have any version that is greater than 455.0.0, you will get this error. To find out what version of the CLI you have installed, run this command:

gcloud --version

The number that’s next to “Google Cloud SDK”, is your CLI version.

As of now, the only solution that I could find is to install version 455.0.0 of the CLI (if you have a newer version). This can be done by running this command:

gcloud components update --version 455.0.0

After downgrading to version 455.0.0, you should be able to deploy your applications without this error. Unfortunately, this is the only solution that I have for now. I will update this post if I find a more permanent solution, but in the meantime, this should get you through.

Please let me know if this does not work for you, or if you find a different solution that works better. You can do this by leaving a comment here, or by sending me an email through my contact page. Thank you!

Update 25-Jan-2024: I upgraded the CLI to v460.0.0, and I can confirm that this issue is now fixed.

A Comprehensive Guide on How to Create Views in MongoDB

MongoDB, an open-source, document-oriented database, has been at the forefront of flexible and scalable data solutions. The NoSQL structure of MongoDB allows it to store substantial amounts of semi-structured data, making it a top choice for big data and real-time web applications. I have talked about how to create relations in MongoDB in this blog post. But have you ever wondered how to create views in MongoDB to streamline your data retrieval and enhance security? Let’s delve into the specifics.

The ability to create views is a standout feature of MongoDB that many developers overlook. In essence, a view is a saved query, providing a virtual subset of data from existing collections without requiring separate data storage. But how does one go about creating views in MongoDB? Let’s explore this further.

Use cases

The use cases for views are numerous, highlighting their potential in data management. A prime reason to create views in MongoDB is to limit data exposure. For instance, if you have a collection with user data, you wouldn’t want every field to be accessible to all users. Creating a view with only the necessary fields provides a way to effectively manage data visibility. Furthermore, views enable you to present a simplified version of your data schema, fostering user-friendly interaction with your data.

Moreover, views in MongoDB are robust tools for complex data operations. Are you joining data across collections or executing complex aggregations? Creating views in MongoDB can be your savior. By encapsulating the query logic in a view, you can conveniently reuse it, saving you from writing complex queries every time, especially with large datasets.

How to create views in MongoDB

So, how to create views in MongoDB? It’s a relatively straightforward process. You use the “db.createView()” function, specifying the view name, source collection, and an aggregation pipeline. For instance, let’s assume we have a collection named “orders,” and we wish to create a view that only displays the “customerName” and “product” fields. The command would look like this:

db.createView(
    "viewOrders",   // the name of the view
    "orders",       // the name of the source collection
    [
        {
            $project : {   // limit the fields to include in the output
                _id : 0,
                customerName : 1,
                product : 1
            }
        }
    ]
);

With the above command, we successfully create a new view called “viewOrders.” This view will only include the “customerName” and “product” fields from each document in the “orders” collection. Learning how to create views in MongoDB offers flexible, secure, and efficient ways to interact with your data.

Conclusion

Whether you are new to MongoDB or a seasoned pro looking to enhance your skills, understanding how to create views in MongoDB is a powerful tool in your developer’s toolkit. Leverage views to provide secure, simplified, and efficient data access, giving your MongoDB usage a substantial boost.

How to add Apple Watch support with Flutter

Flutter is Google’s cross platform development framework. It uses the Dart programming language to create apps for iOS, Android, Web, MacOS, Windows and Linux. There are many advantages to using Flutter. This blog post lists some of them. However, one of the perceived disadvantages of using Flutter, is the fact that it does not support building apps for the Apple Watch. While this is true, the team at Google has provided a way to do that. In this blog post, I will go through the steps required to add Apple Watch Support with Flutter. I will go through a scenario where an existing Flutter app is available, and add support for Apple Watch to it.

For this to work, you will need to make changes on the Flutter side in your preferred editor, like VSCode, (Dart code). And, you will also have to make changes on the iOS side in Xcode (Swift). The idea is that the Flutter code will interact with the native iOS code using messages passed back and forth between the two. This communication is possible through the MethodChannel class on the Flutter side, and FlutterAppDelegate class on the Swift side. In this post, I will only discuss sending messages from Flutter to the native code (the watch), but the other side of the communication uses the same concept.

Changes in Flutter

First step on the Flutter side is to add the following code in the class where you want to send data from:

static const channel = MethodChannel('channel_name');

In the above code, replace channel_name with a name that you know will be unique on the user’s phone and watch. Ideally, the bundle ID of the app, which is usually your company’s domain name in reverse order. This name will be used whenever messages are exchanged between the app on the phone and on the watch. Depending on your existing code, you may have to add this import statement as well.

import 'package:flutter/services.dart';

Now that the channel of communication has been established, the next step is to actually send some data from Flutter to the watch. The below line of code does just that:

await channel.invokeMethod("flutterToWatch", { "method": method_name, "data": some_data });

Here, I’m invoking a method with the name method_name, and sending some_data. This is happening on a channel called flutterToWatch, but it can be anything. Whatever name you choose, this will be the name that the iOS code will be looking for.

This is all that is required on the Flutter side. Next, we will talk about the changes that are required on the iOS (Xcode) side.

Changes in Xcode

First, open the workspace in Xcode. We will have to add a new project to the existing workspace. Go to File -> New -> Target

From this dialog, make sure you go to the watchOS tab, and select App. Then click Next.

From the next dialog, enter a Product Name and select your Team (assuming you are deploying the app to the App Store). And, make sure to select “Watch App for Existing iOS App”. After this step, you should have 2 targets in your Xcode project, one for iPhone (Runner) and a new one for the Watch.

Select the Watch target and click on the Info tab. You should have the following key, WKCompanionAppBundleIdentifier with a value that’s equal to the bundle ID of the iPhone app. And, the Bundle ID of the Watch app should be the bundle ID of the iPhone app followed by .watchkitapp exactly.

Next, open the AppDelegate.swift file and make some modifications. Below is how the file should look like after you complete all the modifications:

import UIKit
import Flutter
import WatchConnectivity
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    var session: WCSession?
    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
    ) -> Bool {
        initFlutterChannel()
        if WCSession.isSupported() {
            session = WCSession.default;
            session?.delegate = self;
            session?.activate();
        }
        
        GeneratedPluginRegistrant.register(with: self)
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    private func initFlutterChannel() {
        if let controller = window?.rootViewController as? FlutterViewController {
            let channel = FlutterMethodChannel(
                name: "channel_name",
                binaryMessenger: controller.binaryMessenger)
            
            channel.setMethodCallHandler({ [weak self] (
                call: FlutterMethodCall,
                result: @escaping FlutterResult) -> Void in
                switch call.method {
                case "method_name":
                    guard let watchSession = self?.session, watchSession.isPaired, watchSession.isReachable, let methodData = call.arguments as? [String: Any], let method = methodData["method"], let data = methodData["data"] else {
                        result(false)
                        return
                    }
                    
                    let watchData: [String: Any] = ["method": method, "data": data]
                    
                    // Pass the receiving message to Apple Watch
                    watchSession.sendMessage(watchData, replyHandler: nil, errorHandler: nil)
                    result(true)
                default:
                    result(FlutterMethodNotImplemented)
                }
            })
        }
    }
}
extension AppDelegate: WCSessionDelegate {
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        
    }
    
    func sessionDidBecomeInactive(_ session: WCSession) {
        
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
        
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        DispatchQueue.main.async {
            if let method = message["method"] as? String, let controller = self.window?.rootViewController as? FlutterViewController {
                let channel = FlutterMethodChannel(
                    name: "channel_name",
                    binaryMessenger: controller.binaryMessenger)
                channel.invokeMethod(method, arguments: message)
            }
        }
    }
}

From the above code, replace channel_name and method_name with the same values that you used in the Dart code on the Flutter side.

That’s it! Now, you can receive the data that’s sent from the iPhone app and use it in the Watch app.

Running in Simulator

To actually run the project in the simulator, you have to do this from Xcode, which means you will not have support for Flutter hot reloading.

From the top of Xcode, change the target to the Watch app, and then click the Start button (play icon). It should look something like this:

If you have any questions, or face issues with this process, please feel free to contact me or comment here.

Updating to Bootstrap 5

Bootstrap is one of the most popular CSS development frameworks used by web developers to create responsive websites. Bootstrap 5, the latest version of this framework, was released in May 2021. If you have previously built a website with Bootstrap 4, you might be wondering if it is worth updating to the latest version. In this blog post, we will discuss the benefits of updating your website from Bootstrap 4 to Bootstrap 5, and some of the steps you need to take to do so.

Why update to Bootstrap 5?

Bootstrap 5 brings some significant changes and improvements over Bootstrap 4. Some of the most notable changes are:

  1. Smaller file size: Bootstrap 5 is designed to be smaller and faster than the previous versions, which means it can help improve the loading speed of your website.
  2. Improved grid system: The new grid system in Bootstrap 5 allows for easier customization and is more flexible than the previous version.
  3. New utility classes: Bootstrap 5 introduces new utility classes that make it easier to style elements and create responsive designs.
  4. New components: Bootstrap 5 introduces several new components, such as the accordion, off-canvas, and toast, which you can use to create modern and interactive user interfaces.

Breaking changes

There are some breaking changes introduced in Bootstrap 5 that you should be aware of. These are just some of the breaking changes introduced in Bootstrap 5. If you are planning to update your website, be sure to review the official Bootstrap 5 documentation for a full list of changes and migration instructions. Additionally, the Bootstrap 5 Upgrade Guide on the Bootstrap website provides detailed information on how to update from previous versions of Bootstrap.

  1. jQuery dependency: Bootstrap 5 no longer requires jQuery, so if you are using jQuery plugins or code, you may need to make some adjustments.
  2. Custom properties: Bootstrap 5 uses custom properties (CSS variables) to define many of its values, which means some of the class names and syntax have changed.
  3. Forms: The structure of forms in Bootstrap 5 has changed, with the introduction of a new .form-control-plaintext class, and the removal of the .form-row class.
  4. Utilities: Some utility classes have been removed or renamed, such as .rounded-0 (renamed to .rounded-), and .img-fluid (renamed to .img-fluid rounded).
  5. Dropdowns: The structure and classes of dropdowns have changed in Bootstrap 5, including the removal of the .dropdown-item-text class.
  6. Card decks: The .card-deck class has been replaced with the new .g- class to provide more flexibility in spacing.

Steps to update from Bootstrap 4 to Bootstrap 5

Updating from Bootstrap 4 to Bootstrap 5 is not a major overhaul, but it does require some changes to your code. Here are some steps you need to take to update your website to Bootstrap 5:

  1. Check compatibility: Before you start updating your website, check if any third-party libraries or plugins you are using are compatible with Bootstrap 5. If not, you may need to find alternatives or wait until the developers of the libraries update them.
  2. Update the CSS and JavaScript files: Download the latest version of Bootstrap 5 and replace the CSS and JavaScript files with the new ones. You can also use a CDN to load the new files.
  3. Update class names: Some class names have changed in Bootstrap 5, so you will need to update them in your HTML and CSS files. For example, the .form-control class is now .form-control-plaintext.
  4. Update custom styles: If you have customized the styles of Bootstrap components, you may need to update them to match the new class names and structure of Bootstrap 5.
  5. Test your website: After updating your website, test it thoroughly to make sure everything is working as expected. Check for any visual issues or broken functionality and fix them as necessary.

Conclusion

Updating from Bootstrap 4 to Bootstrap 5 can bring many benefits to your website, including improved performance, flexibility, and new features. While the update process may require some work, it’s worth it to ensure your website is up to date with the latest technology and standards. By following the steps outlined in this blog post, you can update your website to Bootstrap 5 and take advantage of all the improvements it has to offer. For any questions or comments, please feel free to contact me here.

Update your apps regularly

Most mobile apps on the app stores include third party plugins and libraries that help the app perform certain features. For example, in order to display ads in a Flutter app, you include a third party plugin called google_mobile_ads. This plugin is developed and maintained by a team at Google. All well-maintained plugins are updated from time to time. Each update may include new features and/or, more importantly, security updates.

Keeping your apps in the app stores updated regularly is a very important habit to acquire. And, just to be clear, I’m not talking about publishing updates with new features to the apps (although, this is not a bad thing either!). However, even if you do not have a new feature to publish, it is likely that one or more of the plugins that your app uses, have been updated. If that is the case, then you should include the updated plugin in your app, and publish the updated app to the app store.

Benefits of an App Update

This will accomplish more than one desirable result. First, your app will remain updated with all the security fixes. Keeping your app secure does not involve your code only, but any code that your app uses, including plugins. Second, both Apple and Google have been clamping down on apps that have not been updated for a long time and appear to be abandoned. These apps are ultimately removed from the app stores. And third, users who look at the date when the app was last updated, will more likely going to be installing your app if they see that it has been updated recently.

At W3 Applications, I try to publish an update to every app at least once a month. Even if there are no new features to publish, it is very likely that at least one plugin has been updated in a one month period. That is why I try to update my apps regularly.

Risks in an App Update

An update to any part of a software inherently includes some risks. The biggest risk is that the update might break the app, and make it unusable. This is the worst outcome possible. However, even if the update doesn’t break the whole app, it make break a feature, or a part of the app that some users find useful.

To mitigate this risk, there are certain steps you can take. First, read the release notes of the third party plugin. In some cases, the notes may identify some “Breaking Changes”. If that is the case, then you have to make sure that the breaking change does not affect your app. And, if it does, then you have to change your code to avoid any issues.

Unfortunately, not all release notes identify breaking changes, even if they exist. In cases like this, the best way to avoid issues is to test the update as thoroughly as possible, before publishing to the app store. Ideally, you would want to involve a small subset of your users in the testing process. But, if this option is not available or feasible, then the second best option is to test the update yourself. Test all the features of the app, not only the parts that have been updated. This is because some parts of the app may involve other parts, even if they are not directly related.

Conclusion

Update your apps regularly to keep them secure, and make them more attractive to install. Also, you may end up avoiding having your app removed from the app store for lack of updates.

How to fix the request entity too large error in Express

Express applications that use the body-parser middleware have a default limit to the request body size that the application will handle. This default limit is 100kb. So, if your application receives a request with a body that exceeds this limit, the application will throw a “Error: Request entity too large”. This is a feature that aims to protect your application from potential attacks where the client overloads your application with large requests.

Many resources online will tell you to increase this size to something as large as 25mb or 50mb. Also, you may find websites that tell you to change this limit to request body types that you do not need. My advice is to only change the limit to a size that is reasonable to your case, and only to request body types that you use.

Options

When you create an Express app, you might instantiate the express object with this code:

var app = express();

And, to add the body-parser middleware, you would add this line:

app.use(express.json());

Even if you use the body-parser package, your code may look like this:

const bodyParser = require('body-parser');

app.use(bodyParser.json());

Either way, you are adding the body-parser middleware with the default request body size (100kb);

The Solution

If you know that all your requests will have a json encoded body, then the only change that you need to make is the following:

app.use(express.json({ limit: '200kb' }));

Or;

app.use(bodyParser.json({ limit: '200kb' }));

Notice how I chose a limit of only 200kb, instead of something that’s too large. The size of this limit depends on the type of application and the requests that you expect to handle.

If your requests use url-encoded body, then you will need to use this code:

app.use(express.urlencoded({ limit: '200kb' }));

Or;

app.use(bodyParser.urlencoded({ limit: '200kb' }));

Summary

Express applications that receive a request with a body larger than the set limit (default 100kb), will throw a “Error: Request entity too large”. To change this limit, use something that is reasonable, and not too large. And, finally, change the limit only to the type of requests that you expect.

If you have any questions, please feel free to comment here, or send me a message using the contact page.

Upgrading to Flutter 2.10

The Flutter team at Google has recently released version 2.10 of the popular cross-platform development framework. I wrote about Flutter and the advantages of using it over other frameworks in this post. If you have existing Flutter apps, and you want to upgrade them to the latest version, you may run into issues that you haven’t encountered before (at least that’s what happened with me!). In this blog post, I want to write about a build error that you may encounter after upgrading to the latest version.

The Upgrade

First of all, to actually do the upgrade, you can perform these steps:

  • Make sure you are on the stable channel. To do that, run this command flutter channel in a terminal window to see which channel you’re currently on. If you are not on stable, you can run this command to switch to the stable channel flutter channel stable. Please note that the stable channel is the recommended one because (as the name indicates!) you will get the most stable version of Flutter.
  • Run this command to upgrade to the latest version flutter upgrade.

The Error

After you upgrade, you may get this error when you try to run your app:

Error: Member not found: 'packageRoot'

If you do get this error, then here are a couple of steps you can perform to fix it.

The Fix

I’m going to list the steps that I had to take to fix the error. However, it is very likely that the last step is the only step that you need.

  • Make sure that all of your packages in pubspec.yaml are up to date.
  • In a terminal window, run flutter clean and then flutter pub get. If you still get a build error at this point, try the next step.
  • Run flutter pub upgrade. This will update all your packages, along with their dependancies to the latest version. This step fixed it for me, and I was able to run my app without a build error.

I hope you found this helpful. And, if you have any questions, please don’t hesitate to post them in the comments here, or send me an email through my contact page. Happy coding!

How to create a website without coding

For a small business, there are many benefits to having a company website. You get an online presence 24/7, an ability to expand to more markets outside of your geographical boundaries, and an opportunity for growth. But, not everyone has the technical knowledge or resources to create a website. Yes, there are a lot of website builders that can help with that. However, even those tools also require some technical knowledge. With our Invoicing 24/7 app, you can create a website without coding or technical knowledge.

To get started, download the app from the Apple App Store or Google Play Store, and create your account for free. We designed this app to help small businesses with their invoicing needs. You are also able to create estimates and track projects by time. But the latest update of the app also gives you the ability to create a website for your company. To demonstrate how this works and how the end result looks like, I have setup a page for W3 Applications using the app. You can see the end result here.

Creating the website

From the main screen of the app, hit the “My Website” button. This will take you to a page that allows you to manage your website. But, since we don’t have a website to start with, this page will take you to the website setup screen.

To get started, hit the “My Website” button

The first thing you have to think about, is a name for your website. This name will be part of the address of your page, and once you select one, you can not change. So, think of a name that describes your business well. Ideally, this is the name of your company. In our example, the name of my website is w3applications. This name has to be unique also. That’s why the app will verify that no other website has used it before.

Once a name is selected, you have to type a “Heading” for your website. Again, this is ideally the name of your company and will be displayed prominently in the center when the page is first loaded. Just below the heading is the “Sub Heading”. This is usually the tag line of your company. In my case, the sub heading is “Software solutions for small businesses”.

Changes that you make in the app, reflect on the website

Next, you will add the “Features” that you want to promote on the page. This could be your services, products or anything else you want to highlight on your web page. Each feature has to have a Title, Description and an Image. You can manage all of this right within the app, and it will reflect directly on the website.

Add as many features you want to highlight

Another thing that you can do to add more customization, is to change the color of the website. This should match the brand color of your company.

Also, you can add your company’s email address. This will add a link at the bottom of the page so visitors can send you emails.

That’s it!

And that is all that you need to do to create a website without coding, and that looks professional and provides users with information about your services and products. Once you have added everything, you can then fully manage your web page right from within the app. You can visit the website on your phone to see how it looks like for mobile users, you can edit all the fields described above, copy the URL of the website or share it with anyone.

Managing your website is as easy as tapping a few buttons on your phone

If you have any questions or comments, please send me a message here. Thanks!