How to get csrf token using javascript

i want to get the csrf token and send it in the request using frappe.call()
how can i do it

If you’re using frappe.call you don’t have to do it.

Anyway, if you need it, it’s frappe.csrf_token

1 Like

hi @ankush
thanks for the reply but I am getting csrf token error even after using frappe.call()
here is the error

here is the code

and also when I am console.log(frappe.csrf_token) getting undefined


what is the issue?
so I made a html file in www folder of an app and include a js file in the html using {{ include_script }}
here is the html file

here is the js file

so why I am getting csrf_token error

In Frappe call add header’s

headers: {
            
            'X-Frappe-CSRF-Token': frappe.csrf_token
        },

then validate in python
use frappe.auth.validate_csrf_token for validation
Hope this works
Thanks

when I am doing console.log(frappe.csrf_token) getting undefined and
also there is not header called ‘X-Frappe-Csrf-Token’

why there is no csrf_token in the headers?

try this

frappe.call({
	method: 'your method', // Replace 'your method' with the actual method name
	headers: {
		'X-Frappe-CSRF-Token': frappe.csrf_token
	},
	args: {
		// your arguments go here
		// For example: key1: 'value1', key2: 'value2'
	},
	callback: function (response) {
		frappe.msgprint(response.message);
	}
});

hi @Masky
tried adding

headers: {
‘X-Frappe-CSRF-Token’: frappe.csrf_token
},

still getting same error

hi @ankush there is an update I am getting the csrf_token in the frappe app but when not getting the csrf token for the custom html page which is created in www folder so how can i get the csrf token in custom html

try adding your html,css,js pages in website module > webpages

Maybe you want to do this:



def get_context(context):
	csrf_token = frappe.sessions.get_csrf_token()
	context.csrf_token = csrf_token
	frappe.db.commit()

I ran into this recently, you may have to wrap your frappe.call like this frappe.ready(()=> { frappe.call( ...)} to ensure that the value of frappe.csrf_token is available.

Does this work?

It’s working for me in the context I’m using it in. How are you trying to use it?

const inputElement = document.querySelector('.input-field');
const formElement = document.querySelector('.input-form');

method_url = 'http://10.0.10.139:8000/api/method/erpnext.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field';

const months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

inputElement.addEventListener('keydown', async (e) => {
  try {
    if (e.key === 'Enter') {
      e.preventDefault(); // prevent default behavior
      
      const employeeId = e.target.value;
  
      if (!employeeId) {
        console.log('Invalid Employee ID! Please Try Again');
        throw new Error('Invalid Employee ID!')
      }

      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = months[currentDate.getMonth()];
      const day = currentDate.getDate();
      const hour = currentDate.getHours();
      const minute = currentDate.getMinutes();
      const second = currentDate.getSeconds();
      const milliseconds = currentDate.getMilliseconds();
      const timestamp = `${year}-${month}-${day} ${hour}:${minute}:${second}.${milliseconds}`;

      bodyData = {
        employee_fieldname: "name",
        employee_field_value: employeeId, 
        timestamp: timestamp, 
        log_type: "IN",  
        
      }
     
      const response = await fetch(method_url, {headers: {'Content-Type': 'application/json', 'X-Frappe-CSRF-Token': frappe.csrf_token}, body: JSON.stringify(bodyData), method: 'POST'});

        const data = await response.json();

        if (data.status.startsWith('Success')) {
          console.log(data.status);
        } else {
          console.log(data.status)
        }
      }
  } catch(err) {
    console.error(err);
  } 
});

Oh wow. Frappe uses both jQuery and momentjs. Generally I advise developers to use those because they’re nice shortcuts that are built in; you don’t get ‘cool’ points for not using jQuery.

Wrap every line of code here inside of frappe.ready(() => { ... })

I still get an error saying that frappe is not defined.

How is this code being loaded? Are you putting it in a script tag?

<script src="/assets/check_in/js/index.js"></script>

OK, that should work.
On your portal page, can you access frappe.crsf_token from the JS console?

No I can’t:
ReferenceError: frappe is not defined