This is supplementary information to the workshop for when you may have sensitive environment variables you don’t want exposed on the client.
This can be used in place of the method detailed in:
File based routing in SvelteKit
SvelteKit can utilise HTTP methods for endpoints. These are written in .js
(or .ts
) files that will create handler functions corresponding to HTTP methods. They allow the reading and writing of data that is only available on the server.
Create an endpoint that will map to http://localhost:5173/posts
. Make a posts folder and create the .js
file for the endpoint:
mkdir src/routes/posts.json
touch src/routes/posts.json/+server.js
Create a SECRET_TOKEN
variable in the .env
file:
echo SECRET_TOKEN=this is a secret token >> .env
Add a GET
function in the src/routes/posts.json/+server.js
file using the GraphQL client and giving it the getAllPosts
query:
import { client } from '$lib/graphql/graphql-client';
import { getAllPosts } from '$lib/graphql/graphql-queries';
import { SECRET_TOKEN } from '$env/static/private';
export const GET = async () => {
const { posts } = await client.request(getAllPosts);
// this is only accessible on the server
console.log('=====================')
console.log(SECRET_TOKEN)
console.log('=====================')
return new Response(JSON.stringify(posts, null, 2), {
headers: {
'content-type': 'application/json',
authorization: 'Bearer ' + SECRET_TOKEN
}
});
};