Javascript 401 error

Learn why you may need custom error responses on 4xx errors, what a good custom format looks like, and how to apply it to your error resp...

The 4xx HTTP status codes may not be enough to describe the cause of the error to the client. For this reason, several companies introduced a custom error response format to provide the caller with everything they need to deal with the error. This is a great addition you can make to your backend application, especially considering that implementing it requires only a few lines of code. Let’s see what you need to get started with error response customization for 401 Unauthorized and 403 Forbidden errors in Express.

An Introduction to HTTP Error Status Codes

The HTTP status code is a code number returned by the server in response to a client’s request. The many HTTP status codes available can be grouped into the following five classes based on their number:

  • 1xx: informational responses
  • 2xx: successful responses
  • 3xx: redirection messages
  • 4xx: client error responses
  • 5xx: server error responses

As you can see, there are only two categories of HTTP status codes that represent errors: 4xx and 5xx.

The 4xx class of HTTP status code refers to errors due to the client’s request, for example, because of a malformed request. When it comes to 4xx errors, the server should provide the client with additional info behind the error to prevent it from causing it again.

The 5xx class of HTTP status code refers to errors encountered by the server while processing the request. For security reasons, you should not provide the client with additional info about this type of error. This is because you do not want an attacker to understand how the server works based on what you returned to them.

Using the right HTTP error status codes is important to help the client understand what occurred. In fact, each 4xx or 5xx HTTP status code corresponds to a particular type of error. For example, the 400 status code should be used when the form of the client request is not as the API expects, while the 401 status code should be returned when the client provides no credentials or invalid credentials. However, with 4xx errors, the HTTP status code alone may not be enough, and you should provide the client with more info.

Let’s delve into why you might need to customize your HTTP error responses.

Why Customize Error Responses?

Considering that 4xx errors are caused by the client’s request, not receiving enough info to understand why that request failed may be frustrating. Therefore, you need to customize error responses to provide the client with more details about the problem that occurred. This means returning additional data along with the HTTP error status code.

For example, imagine a situation where an API requires a numeric customerId parameter. Now, a client calls that API without the customerId parameter or using a non-numeric string. As a result, it will receive a generic 400 Bad Request error from the server. As you can imagine, the default «Bad Request» message cannot help the caller understand how they should call the API. On the other hand, if the server returned a 400 HTTP status code response containing the «customerId required» or «customerId must be a number» message, the client could figure out how they need to call the API properly and avoid making the same mistake twice. Therefore, providing a detailed message on 4xx errors helps end-users, and it is also why several companies with public APIs use custom error responses.

Notice that customizing error responses represent a security concern. Although providing extra info in case of errors can be helpful, you should never return info that could jeopardize the security of your application. This is why you should consider customization on error responses only on 4xx errors, which are all directly referable to the client. On the contrary, you should never provide additional info on your 5xx error responses.

Now, let’s see an interesting format for your custom error responses.

A Format for Your Error Responses

To get an idea of how to define a good custom error response format, you can have a look at what reputable companies with public APIs like Google, Apple, and Amazon do in case of errors. For example, this is what GitHub returns in case of a 401 error:

{
   "message": "Requires authentication",
   "documentation_url": "https://docs.github.com/rest/reference/repos#create-an-organization-repository"
}

Returning a string message containing the error description is a common practice, but what is particularly insightful is the documentation_url field. This is a brilliant idea to provide the caller with pathways to solutions and not just report error messages. Also, if something changes, you do not have to update your error responses. What will be changing is the content of the documentation page used in the error response. In addition, returning a public link to the documentation does not pose a security problem by definition because anyone can already access the documentation.

Now, let’s see how to customize your error responses to follow this format in an Express server.

Customize Error Responses in Express

Here, you will learn how to customize the 401 Unauthorized or 403 Forbidden HTTP errors by extending the Auth0 Hello World API. This is a good example of a demo Express application in JavaScript to start from. Also, HTTP 401 and 403 errors fall into the 4xx class and are good examples of errors that may require custom responses.

Let’s now dive into the Auth0 Express Hello World API.

Get started with the Auth0 Hello Word API

You can find the Auth0 Express Hello World API repo here. In detail, let’s focus on the basic-role-based-access-control branch. You can clone it to take a look at its code with the command below:

git clone https://github.com/auth0-developer-hub/api_express_javascript_hello-world.git --branch basic-role-based-access-control

This codebase contains the Express.js Hello World API protected via role validation provided by Auth0. You need an Auth0 account to configure the application, If you don’t have one, sign up for free right now!

Notice that this RBAC (Role-Based Access Control) strategy depends on the Auth0 User Management features. You can learn more about the Express Hello World API with basic RBAC protection here.

Specifically, authentication and authorization error logic is handled in the error.middleware.js file as below:

// src/middleware/error.middleware.js

const errorHandler = (error, request, response, next) => {
  if (error.status === 401 && error.message === "Unauthorized") {
    const status = 401;
    const message = "Requires authentication";

    response.status(status).json({ message });

    return;
  }

  if (
    error.status === 401 &&
    error.code === "invalid_token" &&
    error.message === "Permission denied"
  ) {
    const status = 403;
    const message = error.message;

    response.status(status).json({ message });

    return;
  }

  const status = error.statusCode || error.code || 500;
  const message = error.message || "internal error";

  response.status(status).json({ message });
};

module.exports = {
  errorHandler,
};

Here, the «Unauthorized» 401 error raised by the Auth0 SDK is intercepted and transformed into the following 401 HTTP status code error response:

"Requires authentication"

Similarly, the “Permission denied” 401 error generated by the Auth0 SDK is converted into the following 403 HTTP status code error response:

"Permission denied"

Note that the Auth0 Express library used to provide authorization and authentication does not return a 403 error when the access token is not associated with a user with the expected role, as you might expect. This is because the Auth0 SDK team wanted to keep the library as generic as possible and always returns a generic 401 error. It is up to you to weigh in and determine whether that error returned by the SDK is the most appropriate for your use case. Here, it is not, and that is why the 401 error becomes a 403 error.

Let’s now learn more about the Auth0 library used.

How is access checked?

The Express Hello World API relies on the express-oauth2-jwt-bearer Auth0 library to implement authorization and authentication. If you are not familiar with it, express-oauth2-jwt-bearer is an authentication middleware for Express that validates bearer access tokens in JWT format.

In detail, express-oauth2-jwt-bearer is used in the src/middleware/auth0.middleware.js file as follows:

// src/middleware/auth0.middleware.js

const { auth, claimCheck } = require("express-oauth2-jwt-bearer");
const dotenv = require("dotenv");

dotenv.config();

const validateAccessToken = auth({
  issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
  audience: process.env.AUTH0_AUDIENCE,
});

const checkRequiredPermissions = (requiredPermissions) => {
  return (req, res, next) => {
    const permissionCheck = claimCheck((payload) => {
      const permissions = payload.permissions || [];

      return requiredPermissions.every((requiredPermission) =>
        permissions.includes(requiredPermission)
      );
    }, "Permission denied");

    permissionCheck(req, res, next);
  };
};

module.exports = {
  validateAccessToken,
  checkRequiredPermissions,
};

The validateAccessToken() function is generated by the express-oauth2-jwt-bearer auth() function, which takes a AuthOptions object and returns a middleware function that can be used to restrict an Express endpoint to authorized users. Similarly, the checkRequiredPermissions() function is generated by the express-oauth2-jwt-bearer claimCheck() function, which takes a JWTPayload object and returns a middleware function that can be used to restrict an Express endpoint to authenticated users.

The two functions can be used to provide authentication and authorization as follows:

// src/services/example.js

const express = require("express");
const {
  checkRequiredPermissions,
  validateAccessToken,
} = require("../middleware/auth0.middleware.js");

const messagesRouter = express.Router();

// a public endpoint
messagesRouter.get("/public", (req, res) => {
  res.status(200).json("Hello, World!");
});

// an Express endpoint accessible only by authenticated users
// thanks to the validateAccessToken middleware
messagesRouter.get("/protected", validateAccessToken, (req, res) => {
  res.status(200).json("Hello, World!");
});

// an Express endpoint accessible only by authenticated and authorized users
// thanks to the validateAccessToken and checkRequiredPermissions middleware
// functions respectively
messagesRouter.get(
  "/admin",
  validateAccessToken,
  checkRequiredPermissions(["read:admin-messages"]),
  (req, res) => {
    const message = getAdminMessage();

    res.status(200).json(message);
  }
);

module.exports = { messagesRouter };

Customizing 401 and 403 Error Responses

Let’s now see how to extend the basic-role-based-access-control branch application to implement custom error responses on 401 and 403 errors. You can find the full code in the GitHub repository that supports the article. To achieve the goal, simply change the file error.middleware.js as follows:

// src/middleware/error.middleware.js

const errorHandler = (error, request, response, next) => {
  if (error.status === 401 && error.message === "Unauthorized") {
    // defining the HTTP status code
    const status = 401;
    // standard HTTP 401 error message
    const message = "Unauthorized";
    // the link to the hosted version of the "how-to-handle-authentication" HTML page
    // you can find in the /docs folder
    const authority = `${request.protocol}://${request.hostname}:${process.env.PORT}`;
    const documentationLink = `${authority}/docs/how-to-handle-authentication.html`;

    // implementing a custom error response on 401 errors
    // matching the GitHub error response format
    response.status(status).json({
      message: message,
      documentationLink: documentationLink
    });

    return;
  }

  if (
      error.status === 401 &&
      error.code === "invalid_token" &&
      error.message === "Permission denied"
  ) {
    // defining the HTTP status code
    const status = 403;
    // standard HTTP 403 error message
    const message = "Forbidden";
    // the link to the hosted version of the "how-to-handle-authorization" HTML page
    // you can find in the /docs folder
    const authority = `${request.protocol}://${request.hostname}:${process.env.PORT}`;
    const documentationLink = `${authority}/docs/how-to-handle-authorization.html`;

    // implementing a custom error response on 403 errors
    // matching the GitHub error response format
    response.status(status).json({
      message: message,
      documentationLink: documentationLink
    });

    return;
  }

  const status = error.statusCode || error.code || 500;
  const message = error.message || "internal error";

  response.status(status).json({ message });
};

module.exports = {
  errorHandler,
};

This is what the 401 error response will look like:

{
   "message": "Unauthorized",
   "documentationLink": "https://your-domain.com/docs/how-to-handle-authentication.html"
}

And this is what the 403 error response will look like:

{
   "message": "Forbidden",
   "documentationLink": "https://your-domain.com/docs/how-to-handle-authorization.html"
}

Note that in both cases the error message matches the standard HTTP error message. Also, the links used in the error responses point to the hosted version of the two custom static HTML pages you can find in the /docs folder of the project.

The "How To Handle Authentication" sample doc page

Keep in mind that these HTML documents are only sample pages with lorem ipsum text. Therefore, you should populate the pages with complete information to handle authentication and authorization errors or replace the URLs with appropriate links to your documentation.

Testing the 401 and 403 Error Response

First, clone the extended version of the basic-role-based-access-control Auth0 Hello World API branch with the following command:

git clone https://github.com/auth0-blog/extended-basic-role-based-access-control

Then, enter the extended-basic-role-based-access-control project directory with this command:

cd extended-basic-role-based-access-control

Now, install the npm project dependencies with:

npm install

Then, create a .env file under the root directory of the project and populate it as follows:

PORT=6060
CLIENT_ORIGIN_URL=http://localhost:4040
AUTH0_AUDIENCE=<YOUR-AUTH0-AUDIENCE>
AUTH0_DOMAIN=<YOUR-AUTH0-DOMAIN>

Replace <YOUR-AUTH0-AUDIENCE> and <YOUR-AUTH0-DOMAIN> with the values you can find in the Auth0 dashboard. Also, you will need to retrieve a valid <AUTH0-ACCESS-TOKEN> value. Follow this guide from the official Auth0 documentation to learn how to retrieve these values.

Launch the Express.js API server with the command below:

npm run dev

You are now ready to start testing the 401 error response. For example, let’s try to call the api/messages/protected API that requires authentication without the required Auth0 access token:

curl --request GET 
  --url http:/localhost:6060/api/messages/protected

You will receive a 401 error response containing the following JSON:

{
   "message": "Unauthorized",
   "documentationLink": "https://your-domain.com/docs/how-to-handle-authentication.html"
}

On the contrary, let’s try to use the valid <AUTH0-ACCESS-TOKEN> retrieved earlier.

curl --request GET 
  --url http:/localhost:6060/api/messages/protected 
  --header 'authorization: <AUTH0-ACCESS-TOKEN>'

In this case, you would get:

{
    text: "This is a protected message."
}

Replicating a 403 error requires a little more effort. This is because you need to run a frontend client application that uses the Auth0 SDK. Follow this tutorial from the official documentation to learn how to set up RBAC in Auth0. Make sure to set up a «read:admin-messages» role and associate it with the admin user role.

Then, use any of the Auth0 frontend client demos from the list you can find here to login and access the GET /api/messages/admin endpoint exposed by the Express server launched earlier on port 6060.

When logging with an authorized admin user, you will get:

{
    "text": "This is an admin message."
}

On the other hand, when using an unauthorized user, you will receive the following JSON error response:

{
   "message": "Forbidden",
   "documentationLink": "https://your-domain.com/docs/how-to-handle-authorization.html"
}

Security for Web Developers

Conclusion

In this article, we looked at how to customize error responses when dealing with REST applications developed in Express. This requires just a bunch of lines of code, but you should not take it lightheartedly. On the contrary, it should be implemented with security in mind to avoid providing attackers with useful information about how your backend works. First, we introduced HTTP error status codes and clarified why you might need error response customization on 4xx errors. Then, we studied how companies with public APIs deal with the 4xx errors to define a real-world backed error response format. Finally, we learned how to implement this format when it comes to 401 and 403 errors returned by the Auth0 Express Hello World API using the express-oauth2-jwt-bearer library for authentication and authorization.

Thanks for reading! I hope that you found this article helpful. Feel free to reach out to me with any questions, comments, or suggestions.

As I continue to make the journey from the «traditional» request-response web application design to thick-client, AJAX-driven, realtime applications, I am always finding new problems to solve. Yesterday, on a project, we started seeing an issue where a user would have two tabs open for the same app; then, they would explicitly log-out of one tab which would cause all of the AJAX requests in the other tab to break (they were being diverted to the login page). To fix this in the quickest, easiest way possible, we set up a global AJAX handler that would listen for 401 Status Codes and redirect the user to the login page.

The first part of our problem was that our login page was not returning a 401 status code. This didn’t matter for AJAX requests that were expecting JSON responses (as they would fail anyway); the problem really become obvious with AJAX requests that were expecting HTML responses. To these requests, the Login HTML was just as good as the Modal Window HTML.

By adding a 401 status code to the login page, at least we could start to get all AJAX requests to fail across the board (both those expecting JSON and HTML return data).

Once we got the AJAX requests to start failing, we had to figure out a way to forward the user to the login page once an asynchronous 401 status code was returned. This particular project has a whole mess of AJAX functionality; so, we didn’t want to go through and retrofit each request/response interaction. Instead, we configured a global AJAX handler that listened specifically for the 401 status code; and, if it was triggered, it would use JavaScript to forward the user to the Login page.

To demonstrate this, I put together an extremely simple application that maintains session and has one AJAX request. If you watch the video above, you can see this in action; but, let’s step through the code.

I’m gonna start with the main index page as this is really the only thing worth while — the other pages are just there to support logged-in/logged-out status.

Index.cfm — The «Application» Interface

<!DOCTYPE html>
<html>
<head>
	<title>Handling 401 Errors With jQuery</title>
</head>
<body>

	<h1>
		Handling 401 Errors With jQuery
	</h1>

	<h2>
		Messages From The Server:
	</h2>

	<ul class="messages">
		<!-- To be populated dynamically. -->
	</ul>


	<!-- Include the jQuery library. -->
	<script type="text/javascript" src="../jquery-1.6.1.js"></script>
	<script type="text/javascript">


		// I get the next message from the server.
		function getNextMessage(){

			// Get the message from the server.
			var request = $.ajax({
				type: "get",
				url: "./message.cfm",
				dataType: "json"
			});

			// When the message comes back successfully, add it to
			// the message queue.
			request.done(
				function( response ){

					$( "ul.messages" ).append(
						"<li>" + response + "</li>"
					);

				}
			);

			// When the message comes back as an error, simply alert
			// that the error has occurred.
			request.fail(
				function(){

					alert( "Oops, something went wrong!" );

				}
			);

		}


		// Set up an interval for getting the new messages.
		setInterval( getNextMessage, (5 * 1000) );


		// -------------------------------------------------- //
		// -------------------------------------------------- //


		// Set up a global AJAX error handler to handle the 401
		// unauthorized responses. If a 401 status code comes back,
		// the user is no longer logged-into the system and can not
		// use it properly.
		$.ajaxSetup({
			statusCode: {
				401: function(){

					// Redirec the to the login page.
					location.href = "./login.cfm";

				}
			}
		});


	</script>

</body>
</html>

As you can see, we have one AJAX method — getNextMessage() — that runs on a 5-second interval, requesting messages from the server. Typically, these message requests come back with a 200 OK response and the page is updated accordingly. If, however, the user becomes logged-out, these AJAX requests will start coming back with a 401 Unauthorized response.

To handle this 401 status code, we are using the $.ajaxSetup() function to define a default 401 status code handler. This handler will be merged into all AJAX requests within the entire application (assuming they don’t override it) and will therefore be triggered when any AJAX request comes back with a 401 status code.

NOTE: Status Code callbacks and «error» callbacks co-exist. This means that a 401 status code callback will not prevent an error callback from being used — and vice-versa. Should a 401 error come back, both the error handler and the 401 callback will be invoked.

I don’t know if this is the right way to do things; this is just the first idea that we came up with when we started to see this multi-tab issue arise. And, it seems to have solved the problem reasonably well.

Now that you see how the main, AJAX-driven part of the application is working, let’s quickly run through the support files.

Application.cfc — The ColdFusion Application Framework

<cfcomponent
	output="false"
	hint="I define the application settings and event handlers.">

	<!--- Define the application settings. --->
	<cfset this.name = hash( getCurrentTemplatePath() ) />
	<cfset this.applicationTimeout = createTimeSpan( 0, 0, 10, 0 ) />
	<cfset this.sessionManagement = true />
	<cfset this.sessionTimeout = createTimeSpan( 0, 0, 10, 0 ) />


	<cffunction
		name="onSessionStart"
		access="public"
		returntype="void"
		output="false"
		hint="I initialize the session.">

		<!---
			Keep a simple flag for the user being logged in / out.
			This demo just requires this to be toggled, not really
			functional.
		--->
		<cfset session.isLoggedIn = false />

		<!--- Return out. --->
		<cfreturn />
	</cffunction>


	<cffunction
		name="onRequest"
		access="public"
		returntype="void"
		output="true"
		hint="I execute the incoming request.">

		<!--- Define the arguments. --->
		<cfargument
			name="script"
			type="string"
			required="true"
			hint="I am the script requested by the user."
			/>

		<!---
			Check to see if the user is logged-in. If they are, they
			can execute any script they want; otherwise, they have to
			log-in.
		--->
		<cfif session.isLoggedIn>

			<!--- Execute the requested script. --->
			<cfinclude template="#arguments.script#" />

		<cfelse>

			<!---
				Whoa buddy! You need to be logged-in. Include the
				login page regardless of what script was requested.
			--->
			<cfinclude template="./login.cfm" />

		</cfif>

		<!--- Return out. --->
		<cfreturn />
	</cffunction>

</cfcomponent>

The Application.cfc just defines the application settings and manages the incoming requests. As you can see above, the user’s session has a simple logged-in flag. If the user is logged-in, they can request any script; if they are logged-out, all requests ultimately execute the login page.

The login page then provides hooks to both log into and out of the system:

Login.cfm


<!---
	Check to see if the login has been executed (for this demo, we
	aren't actually using any credentials - we are just toggling the
	logged-in status when requested.
--->
<cfif structKeyExists( url, "login" )>

	<!--- Toggle logged-in status. --->
	<cfset session.isLoggedIn = true />

</cfif>


<!--- Check to see if the logout has been executed. --->
<cfif structKeyExists( url, "logout" )>

	<!--- Toggle logged-in status. --->
	<cfset session.isLoggedIn = false />

</cfif>


<!---
	The user had ended up on the login page. However, they may have
	accessed it directly; or, they may have been forwarded here by
	the security logic. If they were forwarded here, we want to send
	back an unauthorized error.

	NOTE: We could just always send back a 401 status code; but, I
	thought this check might be a bit more elegant.
--->
<cfif (expandPath( cgi.script_name ) neq getCurrentTemplatePath())>

	<!---
		The requested script is NOT the current script - the user
		has been forced to this page for authorization.
	--->
	<cfheader
		statuscode="401"
		statustext="Unauthorized"
		/>

</cfif>


<!--- Reset the output buffer. --->
<cfcontent type="text/html" />

<cfoutput>

	<!DOCTYPE html>
	<html>
	<head>
		<title>Please Login</title>
	</head>
	<body>

		<h1>
			Please Login
		</h1>

		<p>
			Logged-in Status: #session.isLoggedIn#
		</p>

		<p>
			<a href="./index.cfm">Goto homepage</a>.
		</p>

		<p>
			<a href="./login.cfm?login=true">Login</a>
			&nbsp;|&nbsp;
			<a href="./login.cfm?logout=true">Logout</a>.
		</p>

	</body>
	</html>

</cfoutput>

As you can see, this page simply provides a way to toggle the logged-in status of the user for testing purposes. One of the most critical aspects of this page, however, is the fact that the login page returns a 401 Unauthorized status code. It’s this status code that allows the AJAX requests to invoke the proper success and error callbacks.

I could probably have returned the 401 status code all the time; but, for a little added elegance, I am only returning the 401 status code if the user requests a page that is not the login page. So, if they access the login page directly, there is no authorization required.

And, or course, we had our message AJAX request that simply returned a string:

Message.cfm — Our AJAX Target Page

<!--- Define a message. --->
<cfset message = "It is now #timeFormat( now(), 'hh:mm:ss TT' )#" />

<!--- Return the JSON. --->
<cfcontent
	type="application/json"
	variable="#toBinary( toBase64( serializeJSON( message ) ) )#"
	/>

Pretty much nothing going on there.

Again, I don’t know if this is the best way to handle authorization in an AJAX-driven application; but, by making judicious use of the 401 status code and by defining a global 401 AJAX response handler, we were able to fix our problem in just a matter of minutes. Every day, I find a new reason to love jQuery even more!

Want to use code from this post?
Check out the license.

Sai Avinash Duddupudi

Hello everyone,

I am trying to pass access token to an API that returns data through fetch from DATA_API but I am getting 401 unauthorized error.

When I opened Network Tab, I observed that the auth headers did not injected and hence the 401 error is coming. The token is also getting fetched from ACCESS_TOKEN_API and its getting logged in the console.

Here is my code. Please suggest a workaround.

import React, { useState, useEffect } from "react";
import {Col } from 'antd';
import { Link } from "react-router-dom";
import AntDTable from '../shared/AntDTable';
import iInnerLoader from '../shared/iInnerLoader';
const columns = [
  {
    title: 'Account Name',
    dataIndex: 'name',
    render: (text, record) => (
      <Link to={`/all-customers/tenants/?tenant_id=${record.id}&customer=${record.name}`}>{record.name.toUpperCase()}</Link>
    ),
  },
  {
    title: 'Total Tenants',
    dataIndex: 'tenantCount',
  }
];
const useFetch = (url, headers) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
    useEffect(async () => {
      const response = await fetch(url,headers)
      const data = await response.json()
      // console.log(data)
      setData(data)
      setLoading(false)
    },[]);
    return {data, loading};
}
​
export default function CreateTestcaseStep2() {
  const [token, setToken] = useState([]);
    useEffect(async () => {
      const response = await fetch('ACCESS_TOKEN_API',{
        method : 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body : 'body_part'
      })
      const data = await response.json()
      // console.log(data)
      setToken(data)
    },[]);

console.log("token is ", token.access_token) // TOKEN IS GETTING PRINTED HERE
var api_headers={ method: 'GET',
  headers: {'Authorization': `Bearer ${token.access_token}`,
  "Access-Control-Allow-Origin" : "*", 
  "Access-Control-Allow-Credentials" : true },
}
console.log("headers ", api_headers)
  const {data, loading} = useFetch('DATA_API', api_headers)
  return (
    <>
      <Col md={24} sm={24} className="p-0">
        <div className="customer-list">
            <div className="customer-list-header">
              Customer Accounts
            </div>
            <br/>
            <div className="customer-list-content">
            {loading? <iInnerLoader isDisplayLabel={true} label={"Loading Customers"} /> :
             <AntDTable columns={columns} data={data.data} pagination={true} height={390}/>}
            </div>
        </div>
    </Col>
    </>
  );
}

Enter fullscreen mode

Exit fullscreen mode

How to fix the Runtime Code 401 Javascript Error 401

This article features error number Code 401, commonly known as Javascript Error 401 described as Error 401: JavaScript has encountered a problem and needs to close. We are sorry for the inconvenience.

About Runtime Code 401

Runtime Code 401 happens when JavaScript fails or crashes whilst it’s running, hence its name. It doesn’t necessarily mean that the code was corrupt in some way, but just that it did not work during its run-time. This kind of error will appear as an annoying notification on your screen unless handled and corrected. Here are symptoms, causes and ways to troubleshoot the problem.

Definitions (Beta)

Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!

  • Javascript — JavaScript not to be confused with Java is a high-level, dynamic, multi-paradigm, weakly-typed language used for both client-side and server-side scripting

Symptoms of Code 401 — Javascript Error 401

Runtime errors happen without warning. The error message can come up the screen anytime JavaScript is run. In fact, the error message or some other dialogue box can come up again and again if not addressed early on.

There may be instances of files deletion or new files appearing. Though this symptom is largely due to virus infection, it can be attributed as a symptom for runtime error, as virus infection is one of the causes for runtime error. User may also experience a sudden drop in internet connection speed, yet again, this is not always the case.

Fix Javascript Error 401 (Error Code 401)
(For illustrative purposes only)

Causes of Javascript Error 401 — Code 401

During software design, programmers code anticipating the occurrence of errors. However, there are no perfect designs, as errors can be expected even with the best program design. Glitches can happen during runtime if a certain error is not experienced and addressed during design and testing.

Runtime errors are generally caused by incompatible programs running at the same time. It may also occur because of memory problem, a bad graphics driver or virus infection. Whatever the case may be, the problem must be resolved immediately to avoid further problems. Here are ways to remedy the error.

Repair Methods

Runtime errors may be annoying and persistent, but it is not totally hopeless, repairs are available. Here are ways to do it.

If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.

Please note: Neither ErrorVault.com nor it’s writers claim responsibility for the results of the actions taken from employing any of the repair methods listed on this page — you complete these steps at your own risk.

Method 1 — Close Conflicting Programs

When you get a runtime error, keep in mind that it is happening due to programs that are conflicting with each other. The first thing you can do to resolve the problem is to stop these conflicting programs.

  • Open Task Manager by clicking Ctrl-Alt-Del at the same time. This will let you see the list of programs currently running.
  • Go to the Processes tab and stop the programs one by one by highlighting each program and clicking the End Process buttom.
  • You will need to observe if the error message will reoccur each time you stop a process.
  • Once you get to identify which program is causing the error, you may go ahead with the next troubleshooting step, reinstalling the application.

Method 2 — Update / Reinstall Conflicting Programs

Using Control Panel

  • For Windows 7, click the Start Button, then click Control panel, then Uninstall a program
  • For Windows 8, click the Start Button, then scroll down and click More Settings, then click Control panel > Uninstall a program.
  • For Windows 10, just type Control Panel on the search box and click the result, then click Uninstall a program
  • Once inside Programs and Features, click the problem program and click Update or Uninstall.
  • If you chose to update, then you will just need to follow the prompt to complete the process, however if you chose to Uninstall, you will follow the prompt to uninstall and then re-download or use the application’s installation disk to reinstall the program.

Using Other Methods

  • For Windows 7, you may find the list of all installed programs when you click Start and scroll your mouse over the list that appear on the tab. You may see on that list utility for uninstalling the program. You may go ahead and uninstall using utilities available in this tab.
  • For Windows 10, you may click Start, then Settings, then choose Apps.
  • Scroll down to see the list of Apps and features installed in your computer.
  • Click the Program which is causing the runtime error, then you may choose to uninstall or click Advanced options to reset the application.

Method 3 — Update your Virus protection program or download and install the latest Windows Update

Virus infection causing runtime error on your computer must immediately be prevented, quarantined or deleted. Make sure you update your virus program and run a thorough scan of the computer or, run Windows update so you can get the latest virus definition and fix.

Method 4 — Re-install Runtime Libraries

You might be getting the error because of an update, like the MS Visual C++ package which might not be installed properly or completely. What you can do then is to uninstall the current package and install a fresh copy.

  • Uninstall the package by going to Programs and Features, find and highlight the Microsoft Visual C++ Redistributable Package.
  • Click Uninstall on top of the list, and when it is done, reboot your computer.
  • Download the latest redistributable package from Microsoft then install it.

Method 5 — Run Disk Cleanup

You might also be experiencing runtime error because of a very low free space on your computer.

  • You should consider backing up your files and freeing up space on your hard drive
  • You can also clear your cache and reboot your computer
  • You can also run Disk Cleanup, open your explorer window and right click your main directory (this is usually C: )
  • Click Properties and then click Disk Cleanup

Method 6 — Reinstall Your Graphics Driver

If the error is related to a bad graphics driver, then you may do the following:

  • Open your Device Manager, locate the graphics driver
  • Right click the video card driver then click uninstall, then restart your computer

Method 7 — IE related Runtime Error

If the error you are getting is related to the Internet Explorer, you may do the following:

  1. Reset your browser.
    • For Windows 7, you may click Start, go to Control Panel, then click Internet Options on the left side. Then you can click Advanced tab then click the Reset button.
    • For Windows 8 and 10, you may click search and type Internet Options, then go to Advanced tab and click Reset.
  2. Disable script debugging and error notifications.
    • On the same Internet Options window, you may go to Advanced tab and look for Disable script debugging
    • Put a check mark on the radio button
    • At the same time, uncheck the «Display a Notification about every Script Error» item and then click Apply and OK, then reboot your computer.

If these quick fixes do not work, you can always backup files and run repair reinstall on your computer. However, you can do that later when the solutions listed here did not do the job.

Other languages:

Wie beheben Fehler 401 (Javascript-Fehler 401) — Fehler 401: JavaScript hat ein Problem festgestellt und muss geschlossen werden. Wir entschuldigen uns für die Unannehmlichkeiten.
Come fissare Errore 401 (Errore Javascript 401) — Errore 401: JavaScript ha riscontrato un problema e deve essere chiuso. Ci scusiamo per l’inconveniente.
Hoe maak je Fout 401 (Javascript-fout 401) — Fout 401: JavaScript heeft een probleem ondervonden en moet worden afgesloten. Excuses voor het ongemak.
Comment réparer Erreur 401 (Erreur Javascript 401) — Erreur 401 : JavaScript a rencontré un problème et doit se fermer. Nous sommes désolés du dérangement.
어떻게 고치는 지 오류 401 (자바스크립트 오류 401) — 오류 401: JavaScript에 문제가 발생해 닫아야 합니다. 불편을 끼쳐드려 죄송합니다.
Como corrigir o Erro 401 (Erro Javascript 401) — Erro 401: O JavaScript encontrou um problema e precisa fechar. Lamentamos o inconveniente.
Hur man åtgärdar Fel 401 (Javascript-fel 401) — Fel 401: JavaScript har stött på ett problem och måste stängas. Vi är ledsna för besväret.
Как исправить Ошибка 401 (Ошибка Javascript 401) — Ошибка 401: Возникла ошибка в приложении JavaScript. Приложение будет закрыто. Приносим свои извинения за неудобства.
Jak naprawić Błąd 401 (Błąd JavaScript 401) — Błąd 401: JavaScript napotkał problem i musi zostać zamknięty. Przepraszamy za niedogodności.
Cómo arreglar Error 401 (Error de JavaScript 401) — Error 401: JavaScript ha detectado un problema y debe cerrarse. Lamentamos las molestias.

The Author About The Author: Phil Hart has been a Microsoft Community Contributor since 2010. With a current point score over 100,000, they’ve contributed more than 3000 answers in the Microsoft Support forums and have created almost 200 new help articles in the Technet Wiki.

Follow Us: Facebook Youtube Twitter

Recommended Repair Tool:

This repair tool can fix common computer problems such as blue screens, crashes and freezes, missing DLL files, as well as repair malware/virus damage and more by replacing damaged and missing system files.

STEP 1:

Click Here to Download and install the Windows repair tool.

STEP 2:

Click on Start Scan and let it analyze your device.

STEP 3:

Click on Repair All to fix all of the issues it detected.

DOWNLOAD NOW

Compatibility

Requirements

1 Ghz CPU, 512 MB RAM, 40 GB HDD
This download offers unlimited scans of your Windows PC for free. Full system repairs start at $19.95.

Article ID: ACX05562EN

Applies To: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Speed Up Tip #8

Disable Fancy Windows Visual Effects:

If you care about speed more than aesthetics you can always disable those fancy visual effects in Windows. You can do that by going to the Performance Options in your Windows Advanced System Settings. Simply, tick off those fancy buttons, sliding menus, and glossy icons to increase your computer’s performance.

Click Here for another way to speed up your Windows PC

Microsoft & Windows® logos are registered trademarks of Microsoft. Disclaimer: ErrorVault.com is not affiliated with Microsoft, nor does it claim such affiliation. This page may contain definitions from https://stackoverflow.com/tags under the CC-BY-SA license. The information on this page is provided for informational purposes only. © Copyright 2018

Icon Ex Error Number: Error 401
Error Name: Javascript Error 401
Error Description: Error 401: JavaScript has encountered a problem and needs to close. We are sorry for the inconvenience.
Developer: Mozilla Foundation
Software: JavaScript
Applies to: Windows XP, Vista, 7, 8, 10, 11

Examination of Javascript Error 401

Usually, PC practitioners and support staff know Javascript Error 401 as a form of «runtime error». Programmers like Mozilla Foundation endeavor to produce software that is free from these glitches until it is publicly released. Regrettably, issues such as error 401 might not get fixed at this final stage.

«Javascript Error 401» might occur to JavaScript users even through normal use of the application. When this happens, end-users can inform Mozilla Foundation about the presence of Javascript Error 401 bugs. The developer will then be able to rectify its source code and release an update in the market. Consequently, the developer will use a JavaScript update package to resolve error 401 and any other reported error messages.

Why Does Runtime Error 401 Happen?

Failure during JavaScript startup or at runtime is generally when you will encounter Javascript Error 401. We may determine that error 401 runtime errors originate from:

Error 401 Crash — This is a very popular error 401 runtime error that causes the entire program to shut down. Typically this is the result of JavaScript not understanding the input, or not knowing what to output in response.

Javascript Error 401 Memory Leak — If there’s a memory leak in JavaScript, it may cause the OS to appear sluggish. There are some potential issues that may be the reason for getting runtime problems, with incorrect coding leading to infinite loops.

Error 401 Logic Error — A «logic error» is said to be generated when software receives the correct input but generates incorrect output. This is seen when Mozilla Foundation’s source code involves a defect in the input data analysis.

Javascript Error 401 issues are often the result of the file that is missing, deleted, or accidentally moved from JavaScript’s original installed location. The primary way to resolve these problems manually is to replace the Mozilla Foundation file with a fresh copy. Additionally, some Javascript Error 401 errors can be due to incorrect registry references, so we recommend conducting a registry scan to clean up any invalid entries.

Javascript Error 401 Errors

Partial List of Javascript Error 401 JavaScript Errors:

  • «Javascript Error 401 Software Error.»
  • «Win32 Software Error: Javascript Error 401»
  • «Javascript Error 401 needs to close.»
  • «Can’t locate Javascript Error 401»
  • «Javascript Error 401 can’t be found.»
  • «Error starting program: Javascript Error 401.»
  • «Can’t run Javascript Error 401.»
  • «Javascript Error 401 failure.»
  • «Software Path Fault: Javascript Error 401.»

JavaScript Javascript Error 401 issues occur with installation, while Javascript Error 401-related software runs, during shutdown or startup, or less-likely during operating system updates. Notating when Javascript Error 401 errors occur is paramount in finding the cause of the JavaScript problems and reporting them to Mozilla Foundation for help.

Origins of Javascript Error 401 Troubles

These Javascript Error 401 troubles are created by missing or corrupt Javascript Error 401 files, invalid JavaScript registry entries, or malicious software.

Especially, Javascript Error 401 errors stem from:

  • Corrupt Windows registry keys associated with Javascript Error 401 / JavaScript.
  • Javascript Error 401 file corrupted from virus infection.
  • Javascript Error 401 mistakenly deleted or maliciously by software unrelated to the JavaScript application.
  • Javascript Error 401 is in conflict with another program (shared file).
  • Corrupt download or incomplete installation of JavaScript software.

Product by Solvusoft

Download Now
WinThruster 2022 — Scan your PC for computer errors.

Compatible with Windows 11, 10, 8, 7, Vista, XP and 2000

Optional Offer for WinThruster by Solvusoft | EULA | Privacy Policy | Terms | Uninstall

Понравилась статья? Поделить с друзьями:
  • Javafx как изменить сцену
  • Javafx error dialog
  • Javafx alert error
  • Javadoc error cannot read input length 1
  • Javac no source files error