or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ajax-remote.mdcsrf-protection.mddom-utilities.mdelement-state.mdevent-system.mdfeature-handlers.mdform-handling.mdindex.md

csrf-protection.mddocs/

0

# CSRF Protection

1

2

Cross-Site Request Forgery protection system that automatically handles CSRF tokens for all requests and forms, ensuring secure communication with Rails applications.

3

4

## Capabilities

5

6

### CSRF Token Retrieval

7

8

Gets the current CSRF token from the page's meta tags.

9

10

```javascript { .api }

11

/**

12

* Get up-to-date Cross-Site Request Forgery token from meta tag

13

* @returns Current CSRF token or null if not found

14

*/

15

function csrfToken(): string | null;

16

```

17

18

**Usage Examples:**

19

20

```javascript

21

// Get current CSRF token

22

const token = Rails.csrfToken();

23

if (token) {

24

console.log("CSRF Token:", token);

25

}

26

27

// Use in custom AJAX request

28

fetch("/api/data", {

29

method: "POST",

30

headers: {

31

"X-CSRF-Token": Rails.csrfToken(),

32

"Content-Type": "application/json"

33

},

34

body: JSON.stringify({ data: "value" })

35

});

36

```

37

38

### CSRF Parameter Name

39

40

Gets the CSRF parameter name that should be used in forms.

41

42

```javascript { .api }

43

/**

44

* Get URL param name that must contain the CSRF token

45

* @returns CSRF parameter name or null if not found

46

*/

47

function csrfParam(): string | null;

48

```

49

50

**Usage Examples:**

51

52

```javascript

53

// Get CSRF parameter name (typically "authenticity_token")

54

const paramName = Rails.csrfParam();

55

console.log("CSRF param name:", paramName);

56

57

// Build form data with CSRF token

58

const formData = new FormData();

59

formData.append(Rails.csrfParam(), Rails.csrfToken());

60

formData.append("title", "My Post");

61

```

62

63

### Automatic CSRF Protection

64

65

Automatically adds CSRF token to XMLHttpRequest headers for same-origin requests.

66

67

```javascript { .api }

68

/**

69

* Add CSRF token to XHR request headers

70

* @param xhr - XMLHttpRequest instance to add protection to

71

*/

72

function CSRFProtection(xhr: XMLHttpRequest): void;

73

```

74

75

**Usage Examples:**

76

77

```javascript

78

// Manual XHR request with CSRF protection

79

const xhr = new XMLHttpRequest();

80

xhr.open("POST", "/api/data");

81

Rails.CSRFProtection(xhr); // Adds X-CSRF-Token header

82

xhr.send(data);

83

84

// This is automatically called by Rails.ajax() for same-origin requests

85

Rails.ajax({

86

type: "POST",

87

url: "/api/data",

88

data: formData

89

// CSRFProtection is automatically applied

90

});

91

```

92

93

### CSRF Token Refresh

94

95

Updates all form CSRF tokens on the page with the current token value, useful for long-lived pages.

96

97

```javascript { .api }

98

/**

99

* Update all form CSRF tokens with current token from meta tag

100

* Finds all forms with CSRF token inputs and updates their values

101

*/

102

function refreshCSRFTokens(): void;

103

```

104

105

**Usage Examples:**

106

107

```javascript

108

// Refresh all CSRF tokens on the page

109

Rails.refreshCSRFTokens();

110

111

// This is automatically called on DOMContentLoaded

112

// but can be called manually for dynamic content

113

document.addEventListener("DOMContentLoaded", Rails.refreshCSRFTokens);

114

115

// Refresh tokens after AJAX navigation

116

fetch("/new-page")

117

.then(response => response.text())

118

.then(html => {

119

document.body.innerHTML = html;

120

Rails.refreshCSRFTokens(); // Update tokens in new content

121

});

122

```

123

124

## HTML Integration

125

126

CSRF protection relies on meta tags in the HTML head:

127

128

```html

129

<head>

130

<meta name="csrf-param" content="authenticity_token" />

131

<meta name="csrf-token" content="abc123xyz789..." />

132

</head>

133

```

134

135

### Form Integration

136

137

Rails automatically generates hidden CSRF fields in forms:

138

139

```html

140

<form action="/posts" method="post">

141

<input type="hidden" name="authenticity_token" value="abc123xyz789..." />

142

<input type="text" name="title" />

143

<input type="submit" value="Create" />

144

</form>

145

```

146

147

### AJAX Integration

148

149

All AJAX requests made through `Rails.ajax()` automatically include CSRF protection:

150

151

- Same-origin requests get `X-CSRF-Token` header

152

- Cross-origin requests skip CSRF protection

153

- `X-Requested-With: XMLHttpRequest` header identifies AJAX requests

154

155

### jQuery Integration

156

157

When jQuery is present, Rails UJS automatically adds CSRF protection to all jQuery AJAX requests:

158

159

```javascript

160

// Automatically protected when jQuery is available

161

$.ajax({

162

type: "POST",

163

url: "/api/data",

164

data: { title: "My Post" }

165

// X-CSRF-Token header automatically added

166

});

167

```

168

169

### CSP Nonce Support

170

171

Gets Content Security Policy nonce for inline scripts, supporting secure script execution.

172

173

```javascript { .api }

174

/**

175

* Get Content Security Policy nonce for inline scripts

176

* @returns Current CSP nonce or null if not found

177

*/

178

function cspNonce(): string | null;

179

180

/**

181

* Load and cache CSP nonce from meta tag

182

* @returns CSP nonce value or null if not found

183

*/

184

function loadCSPNonce(): string | null;

185

```

186

187

**Usage Examples:**

188

189

```javascript

190

// Get CSP nonce for inline scripts

191

const nonce = Rails.cspNonce();

192

if (nonce) {

193

const script = document.createElement("script");

194

script.setAttribute("nonce", nonce);

195

script.text = "console.log('Secure script');";

196

document.head.appendChild(script);

197

}

198

199

// Load nonce from meta tag (called automatically on DOMContentLoaded)

200

Rails.loadCSPNonce();

201

```

202

203

**HTML Integration:**

204

205

```html

206

<head>

207

<meta name="csp-nonce" content="abc123nonce456" />

208

</head>

209

```

210

211

## Security Considerations

212

213

- CSRF tokens are only added to same-origin requests

214

- Cross-origin requests must handle CSRF protection separately

215

- Tokens should be refreshed periodically for long-lived pages

216

- Meta tags must be present in HTML for token retrieval to work

217

- CSP nonces are used for secure inline script execution when processing JavaScript responses

218

219

## Token Lifecycle

220

221

1. Rails server generates CSRF token and includes in meta tags

222

2. Rails UJS reads token from meta tags on page load

223

3. Token is automatically added to all same-origin AJAX requests

224

4. Form hidden fields are updated with current token value

225

5. Server validates token on protected requests