Client-Side Configuration and Moodle Context
From the 123 curriculum
Client-Side Configuration and Moodle Context
TL;DR
You'll learn how Moodle uses client-side configuration, especially through M.cfg, to pass important settings from the server to your browser. This data defines what your JavaScript can do and how it interacts with the Moodle environment, specifically within different "contexts." Understanding Moodle's context system helps you write secure and efficient client-side code that adapts to where it's being used.
1. The Mental Model
Think of Moodle as a busy office building. Client-side configuration is like the building manager giving you a clipboard with instructions as you walk in: "You're in Department A (context ID 123), so you can use Printer X but not Printer Y." Moodle context is simply knowing where you are in that building – a course, an activity, the site front page – which dictates what resources and permissions are available to you.
2. The Core Material
When Moodle renders a page, it often needs to tell your browser's JavaScript about certain things. This is where M.cfg comes in. M.cfg is a global JavaScript object available on almost every Moodle page. The server fills it with useful information like the current user ID, session key, AJAX URLs, and most importantly, details about the current context.
How M.cfg Gets Populated

Photo by RDNE Stock project on Pexels
Moodle's PHP code builds the M.cfg object. It then injects this as a <script> tag into the HTML head of the page before it's sent to your browser. You can inspect M.cfg in your browser's developer console by typing M.cfg.
Here's a simplified example of what you might see:
// This is what Moodle's PHP outputs to your HTML,
// making M.cfg available globally.
var M = M || {};
M.cfg = {
"wwwroot": "http:\/\/localhost\/moodle",
"sesskey": "aBcDeFgH123",
"theme": "boost",
"lang": "en",
"amd": {"loadon": "body"},
"contextid": 123, // The current context ID
"courseid": 456, // If we're in a course
"cmid": 789, // If we're in a course module
"component": "mod_forum",
"module": "forum",
"userhash": "...",
"pageid": 100,
// ... many more properties
};
Understanding Moodle Context

Photo by Pixabay on Pexels
A context in Moodle represents a specific hierarchical level or "place" within the system. Every item in Moodle – a user, a course, an activity, a block – exists within a context. This context system is fundamental for permissions, file storage, and data isolation.
The hierarchy flows like this:
graph TD
A["System Context (ID 1)"] --> B["Category Contexts (e.g., Cat ID 2)"]
B --> C["Course Contexts (e.g., Course ID 123)"]
C --> D["Module Contexts (e.g., Forum ID 456)"]
D --> E["Block Contexts (e.g., Block ID 789)"]
D --> F["User Contexts (e.g., User ID 10)"]
When you're writing client-side JavaScript, M.cfg.contextid tells you the most specific context ID for the current page. For example, if you're on a forum activity page, M.cfg.contextid will be the context ID of that specific forum module, not just the course. Knowing this ID is crucial when making AJAX calls that require a context, or when determining what features should be available.
Why Context Matters for Client-Side Code

Photo by RealToughCandy.com on Pexels
- Permissions: Your JavaScript code might need to know if the current user has permission to perform an action (e.g., edit a post). While server-side checks are primary,
M.cfgmight expose basic permissions or allow you to pass thecontextidto an AJAX endpoint that performs a permission check. - AJAX Calls: Many Moodle AJAX endpoints require a
contextidto correctly validate permissions and process data. You'll often includeM.cfg.contextidin your AJAX payload. - Data Scoping: Knowing the
courseidorcmid(course module ID) fromM.cfghelps you fetch data relevant to just that course or activity. - Theming/Layout: Sometimes, you might want to apply specific client-side CSS classes or JavaScript behaviors based on the current context (e.g., "if in a quiz, hide this element").
3. Worked Example
Let's say you're developing a custom block that displays a "Mark as Complete" button for the current course module. This button should only appear if the user hasn't completed it and has permission to do so. You need to send the correct cmid and contextid to your server-side AJAX handler.
Here's how you might use M.cfg to get this information:
// Assume this script is loaded on a course module page (e.g., a Forum).
require(['jquery', 'core/ajax'], function($, Ajax) {
$(document).ready(function() {
// M.cfg is already available globally from Moodle's server-side output.
var currentContextId = M.cfg.contextid;
var currentCourseModuleId = M.cfg.cmid; // Specific to a course module page
// Only proceed if we actually have a context and course module ID
if (currentContextId && currentCourseModuleId) {
// Let's say your block adds a button with ID 'mark-complete-button'
$('#mark-complete-button').on('click', function() {
$(this).text('Marking...').prop('disabled', true);
Ajax.call([{
method: 'core_create_completion_record', // A hypothetical AJAX function
args: {
contextid: currentContextId, // IMPORTANT: Pass the context ID
cmid: currentCourseModuleId, // The specific activity to mark
state: 1 // 1 for complete
},
done: function(response) {
if (response.success) {
$('#mark-complete-button').text('Completed!').off('click').addClass('btn-success');
console.log('Activity marked as complete.');
} else {
$('#mark-complete-button').text('Error!').prop('disabled', false).addClass('btn-danger');
console.error('Failed to mark activity complete:', response.error);
}
},
fail: function(error) {
$('#mark-complete-button').text('Network Error!').prop('disabled', false).addClass('btn-danger');
console.error('AJAX request failed:', error);
}
}]);
});
} else {
console.warn('M.cfg.contextid or M.cfg.cmid not found. Cannot enable completion button.');
// Optionally hide the button if context isn't right
$('#mark-complete-button').hide();
}
});
});
In this example, M.cfg.contextid and M.cfg.cmid are directly used to form the AJAX request, ensuring that the server receives the necessary information to process the completion record correctly and securely within the proper context.
4. Key Takeaways
M.cfgis a global JavaScript object Moodle's server populates with vital configuration details for your client-side code.- Always check
M.cfgfor environment-specific data likewwwroot,sesskey,theme, and language. M.cfg.contextidprovides the ID of the current Moodle context, which is crucial for understanding permissions and data scope.- Moodle's context system is a hierarchy (System > Category > Course > Module/Block/User) that defines where an item sits and what resources it can access.
- You'll frequently use
M.cfg.contextidand otherM.cfgproperties when making AJAX calls to Moodle's server-side endpoints. - Client-side configuration helps your JavaScript adapt to different parts of Moodle without needing to re-fetch basic environmental data.
Common Mistakes to Avoid

Photo by KATRIN BOLOVTSOVA on Pexels
- Hardcoding IDs: Never hardcode context, course, or module IDs; always retrieve them from
M.cfgor similar Moodle-provided data. - Ignoring Context: Making AJAX calls without including the relevant
contextidoften leads to permission errors or incorrect data processing. - Over-reliance on
M.cfgfor dynamic data:M.cfgis for initial page load configuration; for real-time dynamic data, use AJAX. - Assuming all
M.cfgproperties are always present: Properties likecmidare only available on specific page types (e.g., course module pages). Always check if a property exists before using it.
5. Now Try It
Open any Moodle course page in your browser where you have editing rights. Open your browser's developer console (usually F12). Type M.cfg and press Enter to inspect its contents. Identify the contextid, courseid, and if you navigate to a specific activity (like a Forum), find cmid. Then, make a small change to a block or activity description, and observe if any new M.cfg values appear or if existing ones update during the page refresh or AJAX call (hint: look at network requests for M.cfg data or similar data payloads).
Frequently asked about Client-Side Configuration and Moodle Context
Study this next
Get the full 123 curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Create Free Account