Connect your content to Nuxt
Assuming you've followed along with the previous steps of configuring schema and editing content, you should be all set up for the next step of bringing your content to the world. Since your content is ultimately just data available through APIs, there’s practically no limit to where you can put it! It doesn’t even have to be the Web, as long as the system can send an HTTP request and do something with the returned JSON data.
In this guide, you will add the necessary code to a Nuxt.js starter in order to pull in your content from your Sanity Content Lake. Below, you’ll find a simple boilerplate as an embedded CodeSandbox project. If you open it in a new window and start editing, it will fork and be tied to your account if you log in. You can also download the code and run it locally, or import it to your GitHub account. To see the finished code, you’ll find another CodeSandbox embed at the end of this guide.
Follow on CodeSandbox or locally
Nuxt.js requires a server, so this is a CodeSandbox Container. These sandboxes can only be forked if you are logged in. To follow along, we recommend you either log in to CodeSandbox, or create an account if you don't have one. Alternatively, you can clone the project from GitHub to your local machine by using the following command:
git clone https://github.com/sanity-io/get-started-sanity-nuxt3.git
and then install the dependencies with
npm install
.
This guide assumes that you have some prior knowledge of Nuxt.js and Vue. If you don’t, but want to learn it, we recommend checking out the official Nuxt.js getting started guide. That being said, this guide has been written intentionally so as to keep the code as simple as possible, so you might be able to tag along here too.
The Nuxt team has made a dedicated module with a lot of built-in functionality for working with content from Sanity in Nuxt.js. In this guide, you’ll only use the module to fetch content.
👉 Add the @nuxtjs/sanity
dependency by searching for it by name in CodeSandBox’s dependency box to the left of the code editor. Clicking it will add it to package.json
as if you were running npm i @nuxtjs/sanity
locally.
Start by adding the following code to the nuxt.config.js
file.
// /nuxt.config.js
import { defineNuxtConfig } from "nuxt";
export default defineNuxtConfig({
modules: ["@nuxtjs/sanity"],
sanity: {
projectId: "YOUR_PROJECT_ID",
apiVersion: '2022-03-25'
},
css: ["@/assets/css/styles.css"]
});
Nuxt.js uses this configuration to load the Sanity module. We only have to tell it the projectId
and apiVersion
as it comes with some built-in defaults.
projectId
: This is the unique identifier for your project that contains all your users, datasets, and other settings. It’s not a secret as it’s part of the URL for your content APIs. You’ll find the project ID in thesanity.json
file in your studio or on the project page onsanity.io/manage
.apiVersion
: Usually, you’d want to put in today’s dateYYYY-MM-DD
to get the newest version of the query API.
While you don’t have to configure the following properties, it can be useful to know about them:
dataset
: This is a collection of documents within a project. You can have multiple datasets (for examplestaging
andproduction
).useCdn
: If you set this totrue
the client will fetch content from our cache delivery network. In this case, however, we will not generate a whole lot of API traffic, and we want updates to be instantly available, so set this tofalse
The next step is to replace the hard-coded data with a data-fetching hook.
👉 Start by adding a variable called query
with the following value:
<!-- // /pages/index.vue -->
<script setup>
const query = groq`*[_type == "pet"]`;
const { data } = {
data: [
/* {
_createdAt: "2022-03-08T09:28:00Z",
_id: "1f69c53d-418a-452f-849a-e92466bb9c75",
_rev: "xnBg0xhUDzo561jnWODd5e",
_type: "animal",
_updatedAt: "2022-03-08T09:28:00Z",
name: "Capybara",
}, */
],
};
</script>
👉 If you remove the comments around the object in the pets
array, you’ll see how the data is rendered.
Here you see some special syntax called a template literal by adding groq
in front of the backticks. This works because the @nuxtjs/sanity
module comes with the groq
package built in. What it does is to give you syntax highlighting for groq queries if your editor supports it (you can install the Sanity extension for VS Code).
👉 Now you can replace the hard-coded array with the useSanityQuery
hook that the module makes available. Pass it the query
variable as its argument.
<!-- // /pages/index.vue -->
<script setup>
const query = groq`*[_type == "pet"]`;
const { data } = useSanityQuery(query);
</script>
The GROQ query filters ([]
) all (*
) your documents down to those with pet
as the value for _type
. If this query works, then it will return an array of documents as objects. Like the one you just removed.
👉 Save your file and see what happens. Did the hardcoded content get replaced by the content you put into the studio? If so, congratulations – you did it! If you add or change content in the studio and publish it, you should be able to refresh the Nuxt.js preview and see it reflect your updates.
In this example, Nuxt.js will run the code inside of <script setup></script>
on the server (or in a serverless function if you have deployed it to production) and generate a JSON file with the data. In this case, there will be no requests to your Sanity Content Lake from the browser at all.
However, if you build out this example (or another Nuxt.js site) and start using its Link
component or other types of data fetching techniques, then Nuxt.js might want to make requests from the browser. This is why you might want to add the CodeSandbox URL to your CORS origins settings, or else it won’t work properly.
Browsers come with security that prevents code injection that steals information from your cookies and passes them to third parties. This is called CORS. To allow your CodeSandbox site to get content from your project, you need to add its URL to your project’s CORS origins settings.
👉 First, grab the URL from the preview pane in your CodeSandbox, it should look something like this https://RANDOM_LETTERS.csb.app/
.
👉 Then head over to the API tab in your project settings at sanity.io/manage. A little bit down the page you'll find the section named "CORS Origins". Click the button labeled "Add CORS Origin", paste the URL from CodeSandbox into the URL field, and hit save (you don’t need to “Allow credentials”). That’s it!