Sub topic 11
Connecting the Salesforce CLI to your org
This chapter assumes you already have a Developer Edition org, can log in through its My Domain URL, and have registered multi-factor authentication. It also assumes you are comfortable running commands in a terminal. By the end, you will have authorized the Salesforce CLI against your org, and you will know what that authorization stores, how to inspect it, and how to fix the usual failures.
What authorization does
The Salesforce CLI is the sf command. It talks to an org through the org's APIs. To do that it needs a credential, and it must not ask for your password on every command. Authorization solves this. You sign in once in a browser, and the CLI stores a token that lets it act as your user afterward.
The default flow is the OAuth 2.0 web server flow with PKCE. The sequence is:
- The CLI starts a small web server on your machine, on port 1717 by default.
- The CLI opens your browser at the org's login page.
- You sign in and approve access for the Salesforce CLI connected app.
- Salesforce redirects the browser to
localhost:1717with an authorization code. - The CLI exchanges the code for an access token and a refresh token, then saves them.
The access token is short-lived. The refresh token lets the CLI get new access tokens without another login, until you revoke it or it expires.
Check the CLI is installed
Run this before you authorize anything.
sf --versionIf the command is not found, install the CLI from the Salesforce developer site (the @salesforce/cli package on npm, or the platform installer). Version 2 of the CLI uses the sf command with topics such as org and data. Older tutorials use sfdx with colon-separated commands like force:auth:web:login. Those still appear in search results, but this tutorial uses the sf forms.
Authorize the org
Run the login command and give the org an alias.
sf org login web --alias my-dev-orgYour browser opens the Salesforce login page. Sign in with your Developer Edition username and password, complete the multi-factor prompt, and click Allow on the access screen. The terminal then prints a message that it successfully authorized your username with the org ID.
An alias is a nickname the CLI stores next to the username. Without one you would have to type something like [email protected] every time. You can use the alias anywhere a command accepts a username.
Useful flags
| Flag | Purpose |
|---|---|
| `--alias` | Nickname for this org, used in later commands. |
| `--set-default` | Makes this org the default target, so you can omit `--target-org`. |
| `--instance-url` | Login URL to use, for example your My Domain URL. |
| `--browser` | Browser to open, such as `chrome`, `firefox` or `edge`. |
| `--no-prompt` | Skips confirmation prompts, useful in scripts. |
A Developer Edition org logs in at https://login.salesforce.com by default, so you normally do not need --instance-url. If your org has My Domain login enforcement or you want the browser to land directly on your org, pass the My Domain URL explicitly.
sf org login web --alias my-dev-org --set-default --instance-url https://my-company-dev-ed.my.salesforce.comReplace the URL with your own My Domain address. Do not use a sandbox login URL (test.salesforce.com) for a Developer Edition org.
List and inspect authorized orgs
Confirm that the CLI recorded the authorization.
sf org listThe output is a table of the orgs the CLI knows about. Look for your alias, the username, the org ID and a connected status. If you have no scratch orgs or sandboxes, you see only the "Other Orgs" section. Orgs that were authorized but are no longer reachable show a status such as RefreshTokenAuthError or Expired.
To see the details for one org, including the instance URL and API version, use the display command.
sf org display --target-org my-dev-orgBy default the output hides the access token. Adding --verbose shows the sfdx auth URL, which contains the refresh token. Treat that value like a password.
Open the org without a password
Once authorized, the CLI can open a browser session that is already signed in.
sf org open --target-org my-dev-orgThe CLI requests a one-time login URL using the stored token and opens it. This is the quickest way to reach the org during development. To land on a specific page, add --path, for example --path lightning/setup/SetupOneHome/home. If you only want the URL, for example to open it in a different browser, add --url-only.
Set defaults so you can type less
Most commands need to know which org to use. You can pass --target-org every time, or set a default.
sf config set target-org my-dev-org
sf config get target-orgBy default sf config set writes to the project's .sf/config.json file, so it must be run inside a Salesforce DX project folder. Add --global to write to your home directory's ~/.sf/config.json instead. A project-level value overrides a global one. Check where a value comes from with sf config list.
Where credentials are stored
The CLI keeps authorization files in a .sfdx folder in your home directory, with one JSON file per username. The files hold the instance URL, the client ID, and the tokens, which are encrypted with a key kept in your operating system's credential store when one is available.
| Item | Location (typical) | Notes |
|---|---|---|
| Auth files | `~/.sfdx/<username>.json` | One per authorized org. |
| Aliases | `~/.sfdx/alias.json` | Maps aliases to usernames. |
| Global config | `~/.sf/config.json` | Written by `sf config set --global`. |
| Project config | `<project>/.sf/config.json` | Overrides the global config. |
Because these files grant access to your org, do not copy them between machines and do not commit them to version control. A project's .gitignore created by the CLI already excludes the .sf and .sfdx folders in the project.
Log out and revoke access
To remove a stored authorization, log out.
sf org logout --target-org my-dev-orgLogging out deletes the local files and prompts you to confirm. It does not delete the org. You can also revoke access on the org side: in Setup, open your user's OAuth Connected Apps Usage or the Connected Apps OAuth Usage page and revoke the Salesforce CLI entry. After a revoke, the CLI can no longer refresh its token, and sf org list shows an authentication error until you log in again.
Verify the connection with a query
Authorization can succeed and the first real API call can still fail, so confirm it with a query. This SOQL query reads the single Organization record.
sf data query --target-org my-dev-org --query "SELECT Name, OrganizationType FROM Organization"A healthy result is a one-row table. OrganizationType should be Developer Edition. If it says something else, you authorized a different org than you intended, which is worth knowing before you deploy anything.
The next check runs in the org itself. Open the Developer Console from the gear menu, choose Debug, then Open Execute Anonymous Apex Window, and run this.
System.debug('Org: ' + UserInfo.getOrganizationName());
System.debug('User: ' + UserInfo.getUserName());Tick Open Log before you run it. In the log, filter for USER_DEBUG to see the org name and username. The username should match the one the CLI printed during login. If the two differ, the CLI is authorized as a different user than the one in your browser.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `command not found: sf` | CLI not installed or not on the path. | Install the CLI, then open a new terminal. |
| Browser opens but the terminal hangs | Port 1717 is in use, or a firewall blocks the redirect. | Close the program using the port, or allow local connections. |
| "redirect_uri_mismatch" or a blank page after login | The redirect to localhost was blocked or altered. | Retry in a different browser and disable extensions that rewrite URLs. |
| Login fails with invalid credentials | Wrong username, or you used the sandbox login URL. | Use your full Developer Edition username and the default login URL. |
| `RefreshTokenAuthError` in `sf org list` | The token was revoked or expired. | Run `sf org login web` again with the same alias. |
| "No default environment found" | No target org set. | Pass `--target-org` or run `sf config set target-org`. |
| Authorized the wrong org | The browser was signed in as another user. | Log out with `sf org logout`, then log in again in a private window. |
| Org inactive or locked | The Developer Edition org was unused for too long. | Log in through the browser to reactivate it, then reauthorize the CLI. |
When a command fails with an unclear message, rerun it with --json to get the full error name and details. The CLI also writes a log file you can inspect, and sf doctor collects diagnostic information that you can attach to a support request.
What you should have now
- An authorized org with the alias
my-dev-org, visible insf org list. - A default target org, if you chose to set one.
- A query result showing
Developer Edition. - A matching username in the CLI output and in the Apex debug log.
The Dev Hub setting you enabled earlier is a separate concern. It lets you create scratch orgs from this org, and the CLI needs this same authorization to do so. You can authorize the org again with --set-default-dev-hub if you want the CLI to treat it as your Dev Hub.
Exercise
You ran sf org login web --alias my-dev-org, and sf data query returns a row where OrganizationType is "Enterprise Edition". What most likely happened, and what do you do next?
Show answer
The browser was signed in to a different org than your Developer Edition org, so the CLI authorized that org under your alias. Run sf org logout --target-org my-dev-org to remove it, then run sf org login web --alias my-dev-org again in a private browser window and sign in with your Developer Edition username. Repeat the query to confirm the result says Developer Edition.
Exercise
sf org list shows your alias with the status RefreshTokenAuthError. The org still works when you log in through the browser. Why does the CLI fail, and how do you fix it?
Show answer
The CLI's stored refresh token is no longer valid, for example because it was revoked under the connected app usage page in Setup or it expired. The org itself is fine. Run sf org login web --alias my-dev-org again to get new tokens, then run sf org list to confirm the status is connected.
Exercise
Why should you avoid sharing the output of sf org display --verbose?
Show answer
With --verbose the output includes the sfdx auth URL, which contains the refresh token. Anyone with it can authenticate as your user in the org until the token is revoked, so treat it like a password.