Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

June 5, 2025

React Dependency Types Explained: What Goes Where in package.json (With Real Examples)

Introduction

When you're working with a React project, you'll often add other packages or tools to help build or run your app. These are called dependencies, and they’re listed in a file called package.json.

But not all dependencies are the same — some are needed in production, some only during development, and some are required only when building reusable libraries.

In this guide, we’ll explain:

  • What dependencies are
  • What devDependencies are
  • What peerDependencies are

with real examples so you can understand when and how to use each.

What are dependencies?

These are the packages your app needs to work when it runs — especially after it's been built and deployed.

When you install a package like this:

it gets added to the dependencies section of package.json.

These will be part of your app’s final bundle that runs in users' browsers.

So here, axios is used for making API calls, and React is your main library. Both are necessary for your app to function properly.

Example:



What are devDependencies?

These packages are only needed while you're developing the app — not when the app is live.

They include things like:

  • Code formatters (eslint)
  • Build tools (vite)
  • Test frameworks (jest)
  • Type checkers (typescript)

You install them using:


They’ll be added to the devDependencies section in package.json.

Example:

When you build your app, these tools help prepare your code — but they’re not included in the final bundle sent to the browser.


What are peerDependencies?

These are a little different. You use peerDependencies mostly when you’re creating a library or shared component, not a full app.

A peerDependency tells the user of your library:

“Hey! You need to have this package installed for my library to work.”

Your library expects the host app to already have that package — usually something like react.

Why do we use this?

If your library includes its own version of React, and the host app uses a different version, they might conflict. That can break things like hooks, context, or even throw errors.

By using peerDependencies, you avoid including React yourself and instead rely on the version the main app already uses.

Example:

This says: “Your project should have a React version that matches one of these.”
npm will warn the user if they don’t.


How npm Handles These Dependencies

When you run:

Here’s what happens for each dependency type:

  • dependencies are always installed and included in the final build.
  • devDependencies are only installed in development, not in production if you set NODE_ENV=production.
  • peerDependencies are not installed automatically in older npm versions (v6 and below).
  • In npm v7+, they try to install them — but only if versions match properly.

Example:

Here:

  • axios is required to run your app.
  • jest is for testing during development.
  • react is expected to be provided by whoever installs your package.


Common Mistakes to Avoid

Here are some mistakes many developers make:

  • Putting everything into dependencies, even tools that are only needed during development.
  • Not adding peerDependencies in libraries — which leads to duplicate versions and weird errors.
  • Including React in both the app and your custom library, causing conflict between React versions.

 

Conclusion

Understanding these three types of dependencies can really improve your project setup:

  • Use dependencies for the actual code your app runs.
  • Use devDependencies for tools that help you build and test.
  • Use peerDependencies when building packages that need shared libraries (like react).

By keeping these organized, your project will stay clean, efficient, and easier to maintain - especially when working with multiple developers or publishing reusable components.

May 8, 2025

Secure Next.js + React Apps: Prevent Injection Attacks with Proper Input Validation Using Yup and DOMPurify

In modern web applications, improper input validation remains one of the most critical and commonly exploited vulnerabilities. This issue arises when user-provided input is not properly validated, sanitized, or filtered before being processed by the application. Improper input validation is one of the most persistent security flaws, often opening doors to client-side and server-side attacks if left unaddressed.


Context and Impact

Improper input validation can lead to significant security risks depending on how user data is processed and stored. If user input is accepted without restrictions, an attacker may inject malicious scripts or unexpected payloads that can exploit the system. These attacks can lead to:

  • Injection Attacks: Including SQL injection, command injection, or script injection.

  • Authentication Bypass: Gaining unauthorized access by manipulating form inputs.

  • Buffer Overflows: Causing memory corruption by supplying unusually large inputs.

  • File Manipulation: Overwriting or accessing sensitive files through poorly validated upload/download mechanisms.

  • Denial of Service (DoS): Causing performance degradation or application crashes through malformed or excessive input.


Best Practices and Remediation (Specific to Next.js + React with Yup)

In a Next.js React application that uses Yup for client-side validation, the following best practices are recommended to mitigate improper input validation risks:

  • Client-Side Validation with Yup: Use Yup schemas to strictly validate form input fields. Ensure that inputs conform to the expected types, formats, and character lengths. For example, email fields should be validated using .email(), numbers can be range-checked using .min()/.max(), and string patterns can be enforced via .matches().
  • Input Sanitization with DOMPurify in Yup: For inputs such as comments, names, or descriptions that accept free text, integrate DOMPurify into Yup’s .test() method to sanitize the content. DOMPurify helps remove or neutralize potentially harmful content such as:

    • Inline <script> tags

    • HTML event handlers (e.g., onerror, onclick)

    • Embedded JavaScript URLs (e.g., javascript:alert('XSS'))

    • <iframe>, <object>, and other suspicious HTML elements

    • Malformed or encoded HTML intended for injection

    Example Implementation (React Hook Form with Yup + DOMPurify)

    Below is a sample implementation that demonstrates how to combine DOMPurify with custom forbidden pattern checks in a Yup schema.

  1. Validation Schema Setup (Yup + DOMPurify)

  2. Using in a React Component (with React Hook Form + Yup)

This ensures only plain text or safe content is submitted, reducing the attack surface for cross-site scripting (XSS) and other injection vectors.
  • Server-Side Validation: Reinforce all client-side checks with server-side validation. Inputs must be re-validated on the backend to ensure no bypass has occurred. Additionally, server-side sanitization should mirror or complement the client-side logic to maintain consistency and security.

By combining schema-based validation using Yup with content sanitization via DOMPurify, the application now effectively filters out potentially malicious input types that could have otherwise led to XSS, layout injection, or DOM manipulation attacks.


Conclusion

Improper input validation is a critical issue that should not be underestimated. In applications built with Next.js and React, adopting a layered approach to input validation—using Yup for schema validation and DOMPurify for sanitization—provides robust defense against injection attacks and other user input-related vulnerabilities. These best practices help secure application workflows and uphold user data integrity.

 If you have any questions you can reach out our SharePoint Consulting team here.

April 18, 2017

Page-break-before doesn't work with IE.

I came across the requirement to print web page using JavaScript. Normally, If we need to add page break while printing the web page, we use "page-break-before" property in CSS. But "page-break-before" does not work with Internet Explorer (IE) browser. Here, I'll show you how we can achieve the desired behavior.

Resolution:

Below is the HTML snippet which is generated using JavaScript. Here, we want to add page break before each Div element. So, I've used "page-break-before:always" style property in each Div element. It will break the page while printing web page. It works fine with "Chrome" or "Mozilla" browsers but it doesn't work with Internet Explorer (IE) browser.

<h1>Page Title</h1>
<!-- content block -->
<!-- content block -->
<div style="page-break-before:always;"></div>
<!-- content block -->
<!-- content block -->
<div style="page-break-before:always;"></div>
<!-- content block -->
<!-- content block -->
<!-- content -->
To have "page-break-before:always" property working in all browsers including Internet Explorer, we need to add one extra Div tag (highlighted) with empty space ("&nbsp;") as shown in below code snippet.

<h1>Page Title</h1>
<!-- content block -->
<!-- content block -->
<div style="page-break-before:always;"></div>
<div>&nbsp;</div>
<!-- content block -->
<!-- content block -->
<div style="page-break-before:always;"></div>
<div>&nbsp;</div>
<!-- content block -->
<!-- content block -->
<!-- content -->
If you have any questions you can reach out our SharePoint Consulting team here.

March 7, 2017

Use Session Storage Object over Local Storage in JavaScript

In few instances, we might come across such requirement where we have to retain/store variable values specific to browser tab over successive post back. Normally, If we open same HTML page in multiple tabs in same browser, then variable value retained over successive post back would be same across all opened tabs. But if requirement is to have different variable values for each opened tab then how would we handle? Lets go through it:

Resolution: As we know, there are two options available in JavaScript to retain values over successive post back.

1. Local Storage
2. Session Storage

We can use Local Storage for saving data in browser over successive post back but there are certain limitations. It will save data in browser but data will remain same for all tabs in browser. In such scenario, where we need separate values for each browser tab, we have to use Session Storage object in JavaScript.

Local Storage:

• It can store data locally within the user's browser.

• Storage limit is far larger (at least 5 MB) and information is never transferred to the server.

• Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

Syntax & Examples for Local Storage:

How to store the value to Local Storage in JavaScript?

Syntax: localStorage.setItem("VariableName", "Value");
Example: localStorage.setItem("BR", "Binary Replublik");

How to retrieve value from Local Storage variable in JavaScript?

Syntax: localStorage.getItem("VariableName") // Returns Object.
Example: document.getElementById("BRTeam").innerHTML = localStorage.getItem("BR");

How to remove Local Storage variable?

Syntax: localStorage.removeItem("VariableName");
Example: localStorage.removeItem("BR");

Session Storage

• The Session Storage object is equal to the Local Storage object, except that it stores the data for only one session. So, the value retained with Session Storage is browser tab specific.

The data will be deleted when the user closes the specific browser tab.

Syntax & Examples for Session Storage:

How to store the value to Session Storage in JavaScript?

Syntax: sessionStorage.setItem("VariableName", "Value");
Example: sessionStorage.setItem("BR", "Binary Replublik");

How to retrieve value from Session Storage variable in JavaScript?

Syntax: sessionStorage.getItem("VariableName") //Returns Object.
Example: document.getElementById("BRTeam").innerHTML = sessionStorage.getItem("BR");

How to remove Session Storage variable?

Syntax: sessionStorage.removeItem("VariableName");
Example: sessionStorage.removeItem("BR");

Conclusion: To store variable value specific to browser tab, we have to deal with session storage over local storage.

If you have any questions you can reach out our SharePoint Consulting team here.

December 16, 2016

SSRS: How to open a linked SSRS Report with parameter in popup

Last month working with SSRS related project, requirement was to open another report on click of date field. Basically, when user clicks on date field in main SSRS report, it should open another report in pop up.

Approach: To achieve the requirement, I've used JavaScript function. Here are the steps , how I have done it !
1. Click on Textbox Property of Date field.
2. Click on Action , Select Go to URL.
3. Click on Expression and apply a code as below.

 ="javascript:void(window.open('" & Cstr(Parameters!BaseUrl.Value) & "?ScheduleId=" & Cstr(Fields!BS_ID.Value) & "','blank','toolbar=no, menubar=no,scrollbars=no, resizable=no, location=no, addressbar=no, left=100,top=100,height=350,width=500'))"  
 
blog16.png

blog17.png

Now, I'll explain you how we can pass BaseURL and other fields as a parameter to generate other SSRS Report. I have a Page named "AdminReport.aspx" which has following code.

 <rsweb:ReportViewer ID="rptViewer" runat="server" Height="500px" Style="-ms-overflow-y: scroll" Width="1100px" ShowToolBar="False" ShowParameterPrompts="False" ShowCredentialPrompts="False"></rsweb:ReportViewer>   

In Code behind of AdminReport Page, I've used below code to bind a second report:
 private void ShowReport()  
     {  
       try  
       {  
         string urlReportServer = ConfigurationManager.AppSettings["ReportViewerUrl"]; //It is a URL Of Report Server.
         rptViewer.ProcessingMode = ProcessingMode.Remote; // Processing Mode will be either Remote or Local.
         rptViewer.ServerReport.ReportServerUrl = new Uri(urlReportServer); //Set the Report Server URL.
         rptViewer.ServerReport.ReportPath = "/AdminReport"; //Set path of Report Page.
         //Create an Array List to combine the Parameters which are to be passed into SSRS Report.  
         ArrayList reportParam = new ArrayList();  
         reportParam = ReportDefaultParam();  
         ReportParameter[] param = new ReportParameter[reportParam.Count];  
         for (int k = 0; k < reportParam.Count; k++)  
         {  
           param[k] = (ReportParameter)reportParam[k];  
         }  
         rptViewer.ServerReport.ReportServerCredentials = new CustomReportServerCredentials();  // Set Credentials.
         rptViewer.ServerReport.SetParameters(param); //Set Report Parameters  
         rptViewer.ServerReport.Refresh();  
       }  
       catch (Exception ex)  
       {  
         CommonUtilities.WriteEventToLogFile(CommonUtilities.GetCurrentTime() + ":AdminViewReport : ShowReport : " + ex.ToString(), "", "", "");  
         // throw ex;  
       }  
     }  
     /// <summary>  
     /// Pass default parameters to the report  
     /// </summary>  
     /// <returns></returns>  
     private ArrayList ReportDefaultParam()  
     {  
       ArrayList arrLstDefaultParam = new ArrayList();  
       string strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;  
       string strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");  
       string baseUrl = strUrl + "ScheduleMaterialReport.aspx";  
       arrLstDefaultParam.Add(CreateReportParameter("BaseUrl", baseUrl));  
       return arrLstDefaultParam;  
     }  
     /// <summary>  
     /// Create report using parameters  
     /// </summary>  
     /// <param name="paramName"></param>  
     /// <param name="pramValue"></param>  
     /// <returns></returns>  
     private ReportParameter CreateReportParameter(string paramName, string pramValue)  
     {  
       ReportParameter aParam = new ReportParameter(paramName, pramValue);  
       return aParam;  
     }  
  • BaseURL - is URL of the second report page, "/SubReport.aspx").
  • BS_ID.value - is the ID (value) of selected record in main Report.
  • ScheduledId - is the field passed as query string parameter to second SSRS report.
We pass this value from main report to other report as query string parameter. E.g.: http://siteurl/SubReport.aspx?ScheduleId=6
 int ScheduleId =Convert.ToInt32(Request.QueryString["ScheduleId"]))  

Now, when user clicks on Date field in Main Report ("AdminReport.aspx" page), other report will open in "SubReport.aspx" page as pop up.

Hope this would be helpful!! If you have any questions you can reach out our SharePoint Consulting team here.

November 23, 2016

Default Print button in SSRS Report is not showing/working in Chrome and Firefox browsers

Scenario
SSRS toolbox provides Print functionality. But it's browser dependent. It works fine only with Internet Explorer browser, not compatible with Firefox and Chrome browsers.

Resolution
To achieve this, we've to use custom Print button and JavaScript code which executes on button click.

HTML code for Print button and Report viewer:
 <asp:Button runat="server" CssClass="btn-addschedule-bot" Style="margin-left: 10px;" ID="btnPrint" CausesValidation="true" ValidationGroup="vgSubmit" OnClientClick="printReportClick();" Text="Print Report" />  
 <div style="border: 1px solid #A7B0E8; margin: 0px 10px; padding: 5px; float: left;">  
 <rsweb:ReportViewer ID="rptViewer" runat="server" Height="500px" Style="-ms-overflow-y: scroll" Width="1100px" ShowToolBar="False" ShowParameterPrompts="False" ShowCredentialPrompts="False"></rsweb:ReportViewer>  
 </div>  

JavaScript Code to print a report in Chrome and Firefox:
 <script type="text/javascript">  
     function printReport(report_ID) {  
       var rv1 = $('#' + report_ID);  
       var iDoc = rv1.parents('html');  
       // Reading the report styles  
       var styles = iDoc.find("head style[id$='ReportControl_styles']").html();  
       if ((styles == undefined) || (styles == '')) {  
         iDoc.find('head script').each(function () {  
           var cnt = $(this).html();  
           var p1 = cnt.indexOf('ReportStyles":"');  
           if (p1 > 0) {  
             p1 += 15;  
             var p2 = cnt.indexOf('"', p1);  
             styles = cnt.substr(p1, p2 - p1);  
           }  
         });  
       }  
       if (styles == '') { alert("Cannot generate styles, Displaying without styles.."); }  
       styles = '<style type="text/css">' + styles + "</style>";  
       //--- Reading the report html  
       var table = rv1.find("div[id$='_oReportDiv']");  
       if (table == undefined) {  
         alert("Report source not found.");  
         return;  
       }  
       //-- Generating a copy of the report in a new window  
       var docType = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd">';  
       var docCnt = styles + table.parent().html();  
       var docHead = '<head><title>Printing ...</title><style>body{margin:5;padding:0;}</style></head>';  
       var winAttr = "location=yes, statusbar=no, directories=no, menubar=no, titlebar=no, toolbar=no, dependent=no, width=720, height=600, resizable=yes, screenX=200, screenY=200, personalbar=no, scrollbars=yes";;  
       var newWin = window.open("", "_blank", winAttr);  
       writeDoc = newWin.document;  
       writeDoc.open();  
       writeDoc.write(docType + '<html>' + docHead + '<body onload="window.print();">' + docCnt + '</body></html>');  
       writeDoc.close();  
       // The print event will fire as soon as the window loads  
       newWin.focus();  
       // uncomment to autoclose the preview window when printing is confirmed or canceled.  
       // newWin.close();  
     };  
     function printReportClick() {  
       printReport('<%=rptViewer.ClientID %>');  
     }  
   </script>  

Print Preview in Chrome browser:



I hope this will help you out to make print functionality working in Chrome and Firefox.

If you have any questions you can reach out our SharePoint Consulting team here.

October 22, 2012

Printing InfoPath Forms

Print option is normally not available as an option on Ribbon in InfoPath templates. So if one wants an option to “Print” InfoPath form then they can use the following steps below. Before starting off the InfoPath should be published as a Content type and a Page with InfoPath form Web Part must be created.
  • Open the Display Form web part page (make sure to select the correct content types if you have more than one....). You can do this by clicking Form Web Parts > (Content Type if you have several) Display Form
  • Edit the InfoPath Form Web Part. Set the Chrome to include just the Title.
  • Add a Content Editor Web part to the page. Set it to Hidden.
  • Add the JS from below link in the HTML source of the Content Editor Web part.
    https://www.nothingbutsharepoint.com/sites/eusp/Pages/jquery-for-everyone-print-any-web-part.aspx
  • Save the page.
You can now click the little icon (or you can modify the JS to insert a button to say 'Print Form') and the Print Preview of the Info Path web part gets opened, along with popup for setting printer options.
In the above JS script, the function “printWebPart” can be modified and replaced by the below script function

  printWebPart(tagid)
        {
            if (tagid)
                {
                    this.print();
                }
        }
 

This will directly open up the popup for setting printer options without showing the Print Preview.

If you have any questions you can reach out our SharePoint Consulting team here.

April 23, 2012

Best Practice: Maintaining scripts in your SharePoint project


Introduction

Branding is the most important part of any SharePoint project. If you are planning to deliver branding in your release, you have to make sure your developer team is proactive to deliver quality branding from early stage of the project. In most of the branding project, jQuery and JavaScript becomes must-have part. Here, we will discuss practices that can be followed to ensure quality deliverables.

Practice
  • Manage script files
    From the very starting stage of your project, split your all JavaScript code in three files.
    • jQuery.min.js - This will contain jQuery reference and should be reference first in order.
    • jQuery.plugins.js - This should contain all custom plugins we used in it.
    • ProjectName.js - This should contain all your custom code written to get your project pages work properly.
  • Choosing plugins for your project
    • Download plugin bundle to your local computer.
    • Generally plugin will contain sample html files, jQuery and plugin script files.
    • First thing to check is jQuery version you are using in your project and the one which is used in the plugin.
    • If they are different, replace their jQuery.min.js with the one we are using.
    • Properly test the sample provided in plugin in all browsers you are planning to support.
    • Once browser and version compatibility matches paste plugin's min.js at end of jQuery.plugins.js file.
    • Implement plugin specific mark up wherever applicable.
    • Always use projectName.js to initialize plugin.
    • Repeat above process when you choose to add any jQuery plugin
  • Resolving CONFLICTS!
    Another challenging part is, jQuery ready not working or custom plugin you are using is disturbing your site's CSS. Here are thoughts on the same:
    • Always use _spBodyOnLoadFunctionNames.Push("yourFunctionName") to initialize your scripts in page load.
    • Always use only necessary CSS from what plugin CSS has provided and prefix class or ID in CSS as application. For example if a generic class .clear is used and you are calling plugin using $('#news') you should replace that with #news .clear. Do this for all CSS you include for the class.
Final thoughts
Here we've pointed out some of the best practices. Like this post? You would like to add/correct something? please provide your feedback on the same. 

If you have any questions you can reach out our SharePoint Consulting team here.

April 2, 2012

How to force browser to clear cache for the Style sheet and Java Script

While googling on to the internet we may found so many solutions for forcing browser to clear the cache for the Stylesheet and javascript using code programatically.

But if we want to do it without any programming using IIS(Interner Information Server)?.

Follow given below steps to do this.

1.From the Start menu, click Administrative Tools, and then click Internet Information Services (IIS) Manager.

2.In the tree view on the left side, find your application.

3. Select the Output Caching menu item.




4. In the right column, click Add in the Action menu. You can add your output caching rule here.




5. In the File name extension field, for example, type .css, and then select User-mode caching and then click on Advanced button.



6. select the Query string variable(s) check box. And enter the appropriate variable(s) in the Query string variable(s) text box as *.



7. Follow this same procedure for javascript , add .js instead of .css in step 5.




Happy coding

Cheers!!!

If you have any questions you can reach out our SharePoint Consulting team here.

March 28, 2012

SP.UI.ModalDialog.showModalDialog not working in chrome

In some version of browser, using will not work due to some reason. I found an alternate method to solve this problem, here is the javascript code:

var dialogSP = null;
if (SP.UI.ModalDialog.showModalDialog) {
dialogSP = SP.UI.ModalDialog.showModalDialog(options);
} else {
dialogSP = SP.UI.ModalDialog.commonModalDialogOpen(countryUrl, options, null, {});
}

If you have any questions you can reach out our SharePoint Consulting team here.