Vanilla JavaScript
Integrate Civic Auth into your Vanilla JavaScript application with just a few lines of code.
Quick Start
Prerequisites
- A Civic Auth Client ID (get it from auth.civic.com)
- Configure your redirect URL in the Civic Auth dashboard (typically
http://localhost:3000
for development)
Installation
NPM
We highly recommend using Vite for the best development experience with modern JavaScript features, fast hot reloading, and seamless ES module support.
Simple Setup
- HTML:
- JavaScript (
main.js
):
That’s it! Replace YOUR_CLIENT_ID
with your actual client ID and you’re done.
Configuration Options
Field | Required | Default | Description |
---|---|---|---|
clientId | Yes | - | Your Civic Auth client ID from auth.civic.com |
targetContainerElement | No | - | DOM element where embedded iframe will be rendered |
redirectUrl | No | Current URL | OAuth redirect URL after authentication |
displayMode | No | modal | How the auth UI is displayed: embedded , modal , redirect , or new_tab |
scopes | No | ['openid', 'profile', 'email'] | OAuth scopes to request |
Display Modes
The displayMode
option controls how the authentication UI is presented:
embedded
(default): The auth UI loads in an iframe within your specified container elementmodal
: The auth UI opens in a modal overlay on top of your current pageredirect
: Full page navigation to the Civic auth server and back to your sitenew_tab
: Opens auth flow in a new browser tab/popup window
Logout
Logging out is very simple.
User object access:
- Use
authClient.getCurrentUser()
to retrieve current user information before logout - Use
authClient.isAuthenticated()
to check if user is currently logged in
Troubleshooting
Module Resolution Error
If you encounter an error like Failed to resolve module specifier "@civic/auth/vanillajs"
, this is typically caused by a corrupted module cache or installation issue.
Solution:
For Vite users:
This issue can occur when switching between different versions of the @civic/auth
package or when the package installation is interrupted.
Common Issues
- CORS errors: Ensure your redirect URL in the Civic Auth dashboard exactly matches your development server URL
- Authentication not starting: Verify your client ID is correct and your redirect URL is properly configured
- Container element not found: Make sure the target container element exists in the DOM before initializing Civic Auth
API Reference
CivicAuth Class
startAuthentication()
Initiates the authentication process.
Returns: Promise that resolves when authentication completes or rejects on error
getCurrentUser()
Retrieves the current authenticated user’s information.
Returns: Promise that resolves to a user object or null if not authenticated
isAuthenticated()
Checks if a user is currently authenticated.
Returns: Promise that resolves to a boolean indicating authentication status
logout()
Logs out the user.
Returns a boolean or throws an error if unsuccessful