Skip to content

Instantly share code, notes, and snippets.

@devyfriend
Last active May 4, 2023 19:05
Show Gist options
  • Save devyfriend/1345d4aba54e8ce1d5c6f9414d40ae19 to your computer and use it in GitHub Desktop.
Save devyfriend/1345d4aba54e8ce1d5c6f9414d40ae19 to your computer and use it in GitHub Desktop.
cheatsheet of sveltekit
export async function load(dd) {}
/*
+layout.server load {
cookies: {
get: [Function: get],
getAll: [Function: getAll],
set: [Function: set],
delete: [Function: delete],
serialize: [Function: serialize]
},
fetch: [Function: fetch],
getClientAddress: [Function: getClientAddress],
locals: {
server: 'http://swacoid.test/',
server_api: 'http://swacoid.test/wp-json/web/v1/'
},
params: {},
platform: undefined,
request: Request {
[Symbol(realm)]: { settingsObject: [Object] },
[Symbol(state)]: {
method: 'GET',
localURLsOnly: false,
unsafeRequest: false,
body: null,
client: [Object],
reservedClient: null,
replacesClientId: '',
window: 'client',
keepalive: false,
serviceWorkers: 'all',
initiator: '',
destination: '',
priority: null,
origin: 'client',
policyContainer: 'client',
referrer: 'client',
referrerPolicy: '',
mode: 'cors',
useCORSPreflightFlag: false,
credentials: 'same-origin',
useCredentials: false,
cache: 'default',
redirect: 'follow',
integrity: '',
cryptoGraphicsNonceMetadata: '',
parserMetadata: '',
reloadNavigation: false,
historyNavigation: false,
userActivation: false,
taintedOrigin: false,
redirectCount: 0,
responseTainting: 'basic',
preventNoCacheCacheControlHeaderModification: false,
done: false,
timingAllowFailed: false,
headersList: [HeadersList],
urlList: [Array],
url: [URL]
},
[Symbol(signal)]: AbortSignal { aborted: false },
[Symbol(headers)]: HeadersList {
cookies: null,
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: null
}
},
route: { id: '/tester' },
setHeaders: [Function: setHeaders],
url: URL {
href: 'http://localhost:3000/tester',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/tester',
search: '',
searchParams: URLSearchParams {},
hash: ''
},
isDataRequest: false,
depends: [Function: depends],
parent: [AsyncFunction: parent]
}
*/
export async function load(dd) {}
/*
+page.js load {
url: URL {
href: 'http://localhost:3000/',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/',
search: '',
searchParams: URLSearchParams {},
hash: ''
},
params: {},
data: {
headlines: [ [Object], [Object], [Object], [Object], [Object] ],
latest: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object]
],
updater: { interval: 420, last_update: 1683214850 },
publishing: { data: [Object], headers: [], status: 200 },
magazine: { data: [Object], headers: [], status: 200 }
},
route: { id: '/' },
fetch: [AsyncFunction (anonymous)],
setHeaders: [Function: setHeaders],
depends: [Function: depends],
parent: [AsyncFunction: parent]
}
*/
/*
+page.js server load {
url: URL {
href: 'http://localhost:3000/',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/',
search: '',
searchParams: URLSearchParams {},
hash: ''
},
params: {},
data: {
headlines: [ [Object], [Object], [Object], [Object], [Object] ],
latest: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object]
],
updater: { interval: 420, last_update: 1683215099 },
publishing: { data: [Object], headers: [], status: 200 },
magazine: { data: [Object], headers: [], status: 200 }
},
route: { id: '/' },
fetch: [AsyncFunction (anonymous)],
setHeaders: [Function: setHeaders],
depends: [Function: depends],
parent: [AsyncFunction: parent]
}
+page.js client load
data, depends, fetch, parent, params, route, setHeaders, url
*/
export async function load(dd) {}
/*
+page.server.js load {
cookies: {
get: [Function: get],
getAll: [Function: getAll],
set: [Function: set],
delete: [Function: delete],
serialize: [Function: serialize]
},
fetch: [Function: fetch],
getClientAddress: [Function: getClientAddress],
locals: {
server: 'http://swacoid.test/',
server_api: 'http://swacoid.test/wp-json/web/v1/'
},
params: {},
platform: undefined,
request: Request {
[Symbol(realm)]: { settingsObject: [Object] },
[Symbol(state)]: {
method: 'GET',
localURLsOnly: false,
unsafeRequest: false,
body: null,
client: [Object],
reservedClient: null,
replacesClientId: '',
window: 'client',
keepalive: false,
serviceWorkers: 'all',
initiator: '',
destination: '',
priority: null,
origin: 'client',
policyContainer: 'client',
referrer: 'client',
referrerPolicy: '',
mode: 'cors',
useCORSPreflightFlag: false,
credentials: 'same-origin',
useCredentials: false,
cache: 'default',
redirect: 'follow',
integrity: '',
cryptoGraphicsNonceMetadata: '',
parserMetadata: '',
reloadNavigation: false,
historyNavigation: false,
userActivation: false,
taintedOrigin: false,
redirectCount: 0,
responseTainting: 'basic',
preventNoCacheCacheControlHeaderModification: false,
done: false,
timingAllowFailed: false,
headersList: [HeadersList],
urlList: [Array],
url: [URL]
},
[Symbol(signal)]: AbortSignal { aborted: false },
[Symbol(headers)]: HeadersList {
cookies: null,
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: null
}
},
route: { id: '/' },
setHeaders: [Function: setHeaders],
url: URL {
href: 'http://localhost:3000/',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/',
search: '',
searchParams: URLSearchParams {},
hash: ''
},
isDataRequest: false,
depends: [Function: depends],
parent: [AsyncFunction: parent]
}
*/
export function handleError({ event, error }) {
console.error("hooks client", error);
}
import { SERVER, SERVER_API } from "$env/static/private";
export async function handle({ event, resolve }) {
event.locals.server = SERVER;
event.locals.server_api = SERVER_API;
return await resolve(event);
}
/*
$env/static/private is a way to access environment variables that are private and known at build time in SvelteKit. These environment variables can be added to a .env file and will be made available to your application1.
It’s important to note that $env/static/private can only be imported into server modules such as +page.server.js, +layout.server.js, +server.js, any modules ending with .server.js, or any modules inside src/lib/server1. This is to prevent sensitive data from accidentally being sent to the browser.
In SvelteKit, $env variables can be either static or dynamic.
Static environment variables are known at build time and can be statically replaced. This enables useful optimizations. For example, if you have a feature flag that is enabled or disabled based on an environment variable, you can use $env/static/private to access the value of that environment variable at build time and optimize your code accordingly.
Dynamic environment variables, on the other hand, are not known until the app is run. These environment variables can be accessed using $env/dynamic/private or $env/dynamic/public, depending on whether they are private or public respectively.
=====================
Sure! Here's an example of using a `static` environment variable in SvelteKit:
Let's say you have a feature flag that is enabled or disabled based on an environment variable. You can add this environment variable to your `.env` file like this:
FEATURE_FLAG_X=enabled
Then, in your server-side code, you can access the value of this environment variable using `$env/static/private` like this:
import { FEATURE_FLAG_X } from '$env/static/private';
if (FEATURE_FLAG_X === 'enabled') {
// code to run if the feature flag is enabled
}
In this example, the value of `FEATURE_FLAG_X` is known at build time and can be statically replaced. This enables useful optimizations such as tree-shaking and dead code elimination.
=====================
Sure! Here's an example of using a `dynamic` environment variable in SvelteKit:
Let's say you have an API key that is not known until the app is run. You can add this environment variable to your `.env` file like this:
API_KEY=myapikey
Then, in your server-side code, you can access the value of this environment variable using `$env/dynamic/private` like this:
import { API_KEY } from '$env/dynamic/private';
// use the API_KEY to make a request to an external API
In this example, the value of `API_KEY` is not known until the app is run. This means that it cannot be statically replaced and must be accessed dynamically at runtime.
========================
The `PUBLIC_` prefix is used to distinguish public environment variables from private environment variables when using `$env/static/public`. For example, if you have an environment variable that can be safely exposed to the browser, you can add it to your `.env` file with a `PUBLIC_` prefix like this:
PUBLIC_THEME_BACKGROUND=steelblue
Then, in your client-side code, you can access the value of this environment variable using `$env/static/public` like this:
import { PUBLIC_THEME_BACKGROUND } from '$env/static/public';
// use the value of PUBLIC_THEME_BACKGROUND in your client-side code
On the other hand, private environment variables do not need a `PRIVATE_` prefix. You can simply add them to your `.env` file without a prefix and access them using `$env/static/private` or `$env/dynamic/private`, depending on whether they are known at build time or not.
Does this help clarify the use of the `PUBLIC_` prefix and the absence of a `PRIVATE_` prefix?
*/
+page.svelte file is a Svelte component that represents a page in your SvelteKit application.
+page.js file is a sibling file to the +page.svelte file that can export a load function,
which is used to load data before rendering the page.
+page.server.js file is similar to a +page.js file, but its load function only runs on the server.
Similarly,
+layout.svelte file is a Svelte component that represents a layout for one or more
pages in your SvelteKit application.
+layout.js file is a sibling file to the +layout.svelte file that can also export a load function,
which is used to load data before rendering the layout.
+layout.server.js file is similar to a +layout.js file, but its load function only runs on the server.
====================
"export async function load" in a +page.js file or a +layout.js file runs both on the server and in the browser.
====================
hooks.server.js and hooks.client.js are optional files in a SvelteKit project
that contain app-wide functions that SvelteKit will call in response to specific events,
giving you fine-grained control over the framework’s behavior.
Code in these modules will run when the application starts up,
making them useful for initializing database clients and so on
// src/hooks.server.js
export async function handle({ event, resolve }) {
// Add custom data to the request
event.locals.user = await getUserInformation(event.cookies.get('sessionid'));
// Generate the response by rendering the route
const response = await resolve(event);
// Modify the response headers
response.headers.set('x-custom-header', 'potato');
return response;
}
===============================================
// src/hooks.server.js
export async function handle({ event, resolve }) {
// Check if the request is for the /data route
if (event.url.pathname === '/data') {
// Create a JSON response
const body = JSON.stringify({ message: 'Hello, world!' });
const headers = { 'Content-Type': 'application/json' };
return new Response(body, { headers });
}
// For other routes, generate the response by rendering the route
return await resolve(event);
}
This handle hook checks if the request is for the /data route.
If it is, it creates a JSON response by calling JSON.stringify
with an object containing the data to be sent.
It then creates a headers object with the Content-Type set to application/json.
Finally, it returns a new Response object with the JSON data as the body and the headers.
For other routes, it generates the response by calling the resolve function with the event object
================================================
In SvelteKit, you can handle GET and POST requests by defining get and post
handlers in a +page.server.js file or a +server.js file.
Here is an example of a +page.server.js file that defines both a get handler and a post handler:
// src/routes/api/+page.server.js
export async function get(request) {
// Handle GET request
return {
body: { message: 'Hello from GET handler' }
};
}
export async function post(request) {
// Handle POST request
return {
body: { message: 'Hello from POST handler' }
};
}
This +page.server.js file exports two functions: get and post.
The get function is called when the server receives a GET request for the /api route.
The post function is called when the server receives a POST request for the /api route.
Both functions return an object with a body property that contains the data to be sent in the response
=================================================
Yes, get and post handlers in a +page.server.js file or a +server.js file can return JSON data.
Here is an example of a +page.server.js file that defines both a get handler and a post handler
that return JSON data:
// src/routes/api/+page.server.js
export async function get(request) {
// Handle GET request
return {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Hello from GET handler' })
};
}
export async function post(request) {
// Handle POST request
return {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Hello from POST handler' })
};
}
This +page.server.js file exports two functions: get and post.
The get function is called when the server receives a GET request for the /api route.
The post function is called when the server receives a POST request for the /api route.
Both functions return an object with a headers property that sets the Content-Type to application/json,
and a body property that contains the JSON data to be sent in the response
======================================================
One way to load data from an endpoint and wait until it is received and
validated before entering certain routes in a SvelteKit application is to
use a load function in a +page.js or +page.server.js file.
Here is an example of a +page.server.js file that defines a load function
that fetches data from an endpoint and validates it before rendering the page:
// src/routes/protected/+page.server.js
export async function load({ fetch }) {
// Fetch data from endpoint
const response = await fetch('/api/data');
const data = await response.json();
// Validate data
if (!data.valid) {
// Redirect to login page if data is not valid
return {
status: 302,
redirect: '/login'
};
}
// Pass data to page component
return {
props: { data }
};
}
This load function uses the fetch function provided by
SvelteKit to fetch data from the /api/data endpoint.
It then calls the json method on the response object to parse the JSON data.
The function then checks if the valid property of the data object is false.
If it is, the function returns an object with a status property set to 302
and a redirect property set to /login, which redirects the user to the /login page.
If the valid property of the data object is not false, the function returns an object
with a props property that contains the data object,
which is passed to the page component
=====================================================
// src/routes/protected/+page.js
export async function load({ fetch }) {
// Fetch data from endpoint
const response = await fetch('/api/data');
const data = await response.json();
// Check if localStorage is available
if (typeof localStorage !== 'undefined') {
// Store data in localStorage
localStorage.setItem('data', JSON.stringify(data));
}
// Validate data
if (!data.valid) {
// Redirect to login page if data is not valid
return {
status: 302,
redirect: '/login'
};
}
// Pass data to page component
return {
props: { data }
};
}
==========================================================================
In SvelteKit, the +server.js file is used to define server-side logic for a layout or page component. This file can contain code that is intended to run only on the server-side, such as code that interacts with a database or a storage solution.
Here are some common use cases for the +server.js file:
Defining the load function: The load function is used to fetch data on the server-side and pass it to the page or layout component as props. You can define the load function in the +server.js file to fetch data from a database or an API and pass it to the component.
Defining server-side actions: You can define server-side actions in the +server.js file to handle form submissions or other requests from the client-side. Server-side actions can interact with a database or a storage solution to perform operations such as creating, updating, or deleting data.
Importing private environment variables: You can use the +server.js file to import private environment variables from $env/static/private. These variables can be used in your server-side code to access sensitive information such as API keys or database credentials.
The +server.js file provides a way to define server-side logic for your SvelteKit components.
Here is an example of a `+server.js` file that defines a `load` function and a server-side action for a page component:
```js
// src/routes/+page/+server.js
import { db } from '$lib/db';
export async function load({ params }) {
// Fetch data from database
const data = await db.getData(params.id);
// Pass data to page component
return {
props: { data }
};
}
export const actions = {
submit: async ({ request }) => {
// Parse form data
const formData = await request.formData();
const name = formData.get('name');
const email = formData.get('email');
// Store data in database
await db.storeData(name, email);
// Redirect to success page
return {
status: 302,
redirect: '/success'
};
}
};
```
This `+server.js` file defines a `load` function that fetches data from a database and passes it to the page component as props. It also defines a server-side action named `submit` that handles form submissions from the client-side. The `submit` action parses the form data and stores it in the database. After storing the data, it redirects the user to a success page.
This is just one example of how you can use the `+server.js` file to define server-side logic for your SvelteKit components. Does this help?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment