Integrate authentication into Vue.js + API
This guide shows how to create a simple Vue.js application and secure it with authentication powered by Ory. The guide provides the setup for using Ory Network, but the code can be used with both Ory Network and self-hosted Ory software.
This guide is perfect for you if:
- You have Vue.js installed.
- You want to build an app using Vue.js.
- You want to give access to your application to signed-in users only.
Before you start, watch this video to see the user flow you're going to implement:
You can find the code of the sample application here.
Create Vue.js app
First, create a new Vue.js project. Run:
npm create vue@latest -- --default
cd app-name
npm install
Create a new Ory project
- Create an Ory account at https://console.ory.sh
- Create a new project at https://console.ory.sh/projects/create
- Go to your project settings
- Note down your project credentials (ID, slug, endpoint)
Install Ory SDK and CLI
To interact with Ory's APIs we install the Ory SDK and CLI:
npm i --save @ory/client-fetch @ory/cli
Why do I need the Ory CLI
The Ory security model uses HTTP cookies to manage sessions, tokens, and cookies. Because of browser security measures like CORS, Ory APIs must be exposed on the same domain as your application.
In the case of this example the application runs on your local machine. The cookie domain is localhost
.
When developing locally, use either localhost
or 127.0.0.1
, but not both. Although technically these mean the same thing,
they're different cookie domains.
Using both interchangeably in your code causes problems, as Ory APIs will not receive the cookies when they are set on a different domain.
Ory CLI provides a convenient way to configure and manage projects. Additionally, the CLI provides Ory Tunnel - a reverse proxy that rewrites cookies to match the domain your application is currently on.
To make Ory APIs and your application available on the same domain, Ory Tunnel mirrors Ory endpoints and rewrites cookies to match the domain correct domain.
As a result, the domain of the cookies is set correctly to the domain you run the app on instead of
<your-project-slug>.projects.oryapis.com
.
By using the Tunnel, you can easily connect the application you're developing locally to Ory Network and consume the APIs without additional configuration or the self-hosting any Ory services.
To learn more about the Ory Tunnel, read the dedicated section of the Ory CLI documentation.
Run Ory APIs on localhost
In a new terminal window, run the Ory Tunnel:
npx @ory/cli tunnel --dev http://localhost:5173
This command mirrors Ory APIs on http://localhost:4000
. Use that URL as the baseUrl
for the @ory/client-fetch
SDK (see
App.vue
code below). The --dev
flag disables security checks for easier integration and should not be used when running the
Tunnel in an insecure environment like public networks.
Authenticate user
To implment authentication, modify the existing App.vue
component to include the following:
<template>
<div class="main">
<h1>{{ msg }}</h1>
<div v-if="!session">
<p>Click on "login" or "Sign Up" below to sign in.</p>
<li><a :href="basePath + '/ui/login'" data-testid="sign-in">Login</a></li>
<li>
<a :href="basePath + '/ui/registration'" data-testid="sign-up"
>Sign Up</a
>
</li>
</div>
<h3 v-if="session">Calling <code>toSession()</code></h3>
<div v-if="session" class="long">
<p>
Use the SDK's <code>toSession()</code> call to receive the session
information, for example the authentication methods used:
</p>
<pre><code data-testid='ory-response'>{{ session.authentication_methods }}</code></pre>
</div>
<h3 v-if="session">Common Actions</h3>
<ul v-if="session">
<li><a :href="logoutUrl" data-testid="logout">Logout</a></li>
<li>
<a :href="basePath + '/ui/settings'" data-testid="settings">Settings</a>
</li>
</ul>
<h3>Essential Links</h3>
<ul>
<li><a href="https://www.ory.sh">Ory Website</a></li>
<li><a href="https://github.com/ory">Ory GitHub</a></li>
<li><a href="https://www.ory.sh/docs">Documentation</a></li>
</ul>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue"
import { FrontendApi, Configuration } from "@ory/client-fetch"
const props = defineProps({
msg: String,
})
// State variables
const session = ref(null)
const logoutUrl = ref(null)
const basePath = import.meta.env.VITE_ORY_URL || "http://localhost:4000"
console.log("basePath", basePath)
// Initialize Ory client
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)
const fetchSession = async () => {
try {
// Fetch the session directly from Ory
const data = await ory.toSession()
session.value = data
// Create logout URL if session exists
const logoutData = await ory.createBrowserLogoutFlow()
logoutUrl.value = logoutData.logout_url
} catch (error) {
console.error("Error fetching session:", error)
}
}
// Lifecycle hooks
onMounted(async () => {
// Fetch the session and API response
await fetchSession()
})
</script>
<style scoped>
.main {
max-width: 400px;
margin: 0 auto;
}
</style>
The component checks whether a user is signed in and if so, shows a logout link and the user's session information. Otherwise, it shows a login and registration link.
Run your Vue.js app
Now that your app is ready, it's time to run it! Start the Vue development server:
npm run dev
Go to localhost:5173 to access your application.
Make authenticated calls to your API
To make authenticated requests to your API there are two main components:
- When making AJAX requests you must set
{"credentials": "include"}
in the options. For thefetch
method it looks like this:
<template>
<div class="main">
<h1>{{ msg }}</h1>
<div v-if="!session">
<p>Click on "login" or "Sign Up" below to sign in.</p>
<li><a :href="basePath + '/ui/login'" data-testid="sign-in">Login</a></li>
<li>
<a :href="basePath + '/ui/registration'" data-testid="sign-up"
>Sign Up</a
>
</li>
</div>
<h3 v-if="session">Calling <code>toSession()</code></h3>
<div v-if="session" class="long">
<p>
Use the SDK's <code>toSession()</code> call to receive the session
information, for example the authentication methods used:
</p>
<pre><code data-testid='ory-response'>{{ session.authentication_methods }}</code></pre>
</div>
<h3 v-if="apiResponse">API Response</h3>
<div v-if="apiResponse" class="long">
<p>
Make authenticated AJAX calls to your API using <code>fetch()</code>:
</p>
<pre><code data-testid='api-response'>{{ apiResponse }}</code></pre>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue"
import { FrontendApi, Configuration } from "@ory/client-fetch"
const props = defineProps({
msg: String,
})
// State variables
const session = ref(null)
const logoutUrl = ref(null)
const apiResponse = ref(null)
const basePath = import.meta.env.VITE_ORY_URL || "http://localhost:4000"
const apiUrl = import.meta.env.VITE_API_URL || "http://localhost:8081"
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)
const fetchSession = async () => {
try {
const data = await ory.toSession()
session.value = data
const logoutData = await ory.createBrowserLogoutFlow()
logoutUrl.value = logoutData.data.logout_url
} catch (error) {
console.error("Error fetching session:", error)
}
}
const fetchApiHello = async () => {
try {
const res = await fetch(`${apiUrl}/api/hello`, {
// Do not forget to set this - it is required to send the session cookie!
credentials: "include",
})
if (res.ok) {
const data = await res.json()
apiResponse.value = data
}
} catch (error) {
console.error("Error fetching API response:", error)
}
}
// Lifecycle hooks
onMounted(async () => {
await fetchSession()
// Make an authenticated API call
await fetchApiHello()
})
</script>
<style scoped>
.main {
max-width: 400px;
margin: 0 auto;
}
</style>
- Your API must have a CORS middleware with
credentials: true
andAccess-Control-Allow-Origin
of your frontend app (herehttp://localhost:8080
).
Let's put this into action. Create a simple HTTP API with express. Run:
mkdir api
cd api
npm init
npm i --save @ory/client-fetch express cors
Next, create a simple API in index.js
:
const express = require("express")
const cors = require("cors")
const { FrontendApi, Configuration } = require("@ory/client-fetch")
const app = express()
const ory = new FrontendApi(
new Configuration({
// Points to the local Ory API server (Ory TunneL).
basePath: process.env.ORY_URL || "http://localhost:4000",
baseOptions: { withCredentials: true },
}),
)
app.use(
cors({
origin: process.env.UI_URL || "http://localhost:8080",
credentials: true, // <- Required for CORS to accept cookies and tokens.
}),
)
app.use((req, res, next) => {
// A simple middleware to authenticate the request.
ory
.toSession({
// This is important - you need to forward the cookies (think of it as a token)
// to Ory:
cookie: req.headers.cookie,
})
.then(({ data }) => {
req.session = data
next()
})
.catch(() => {
res.status(401)
res.json({ error: "Unauthorized" })
})
})
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from our API!",
session_id: req.session.id,
identity_traits: req.session.identity.traits,
})
})
const port = process.env.PORT || 8081
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Finally, start the server:
node index.js
See it in action
Access your single-page app at localhost:8081, sign in, and see if you can make authenticated requests to your API!
Go to production
To promote this app to production:
- Build the VueJS app and run it somewhere (for example on Vercel or Netlify)
- Deploy the API (for example, on Heroku)
- Connect your project with a custom domain
These three components must be hosted on the same top-level domain as they were on your local machine:
Component | Production | Local |
---|---|---|
Single Page App | www.example.org | localhost:8080 |
API | api.example.org | localhost:3000 |
Ory | ory.example.org | localhost:4000 |